Home > Enterprise >  Deleting certain part of file names
Deleting certain part of file names

Time:07-19

I have a set of file names I am looping over to delete one aspect at the end of all file names. Currently I have some code that will search for a string in the filename and delete it. However the part of the file I want to get rid of changes a little. I was looking to use some characters one would use for glob.glob(file) but Im sure you can't do that. Is there a way to do this? Maybe split() and rewrite the name?

Here are a couple files. I want to get rid of the (Ni??Nj??)

a-optimized.new.10_10_50-775-11_11_60.Ni01Nj10.txt
a-optimized.new.10_10_60-755-11_11_60.Ni00Nj01.txt
a-optimized.new.10_10_40-715-11_11_60.Ni00Nj10.txt

here is the code I am working with

import os
rootdir = r"C:\Py Practice\Sorted File Groups\nmdAnmd"
str = ".Ni*Nj*"
for filename in os.listdir(rootdir):
    if str in filename:    
        filepath = os.path.join(rootdir, filename)
        newfilepath = os.path.join(rootdir, filename.replace(str, ""))
        os.rename(filepath, newfilepath)

CodePudding user response:

You could use a matching pattern instead and replace with an empty string.

\.Ni\d*Nj\d*

The pattern matches:

  • \.Ni Match .Ni
  • \d* Match optional digits
  • Nj Match Nj
  • \d* Match optional digits

Example

import os
import re

rootdir = r"C:\Py Practice\Sorted File Groups\nmdAnmd"
pattern = r"\.Ni\d*Nj\d*"

for filename in os.listdir(rootdir):
    filepath = os.path.join(rootdir, filename)
    newfilepath = os.path.join(rootdir, re.sub(pattern, "", filename))
    os.rename(filepath, newfilepath)

Output

a-optimized.new.10_10_50-775-11_11_60.txt
a-optimized.new.10_10_60-755-11_11_60.txt
a-optimized.new.10_10_40-715-11_11_60.txt
  • Related