0

Suppose I have a bunch of files labeled as such:

  • SUS200_One.txt
  • SUS300_Two.txt
  • SUS400_Three.txt

I want to remove the SUSxxx portion of each txt file in a certain directory. I have the regular expression pattern correct and I'm able to find the expression on each file when I perform a loop on the directory. However, I just don't know how I go about removing it. For example, I want each file to have the SUSXXX removed and have each file left with _One, _Two, _Three, respectively. Below is what I have so far. For some reason, I cannot figure this out, as simple as this may be. Any help would be appreciated.

rootdir = ('C:\\Test')
pattern = re.compile(r'\w{3}\d{3}')

def removeChar():
    for filename in os.listdir(rootdir):
        findpattern = pattern.findall(filename)
    
removeChar()
Machavity
  • 30,841
  • 27
  • 92
  • 100
gq1108
  • 5
  • 1
  • 3
    Does this answer your question? [How to input a regex in string.replace?](https://stackoverflow.com/questions/5658369/how-to-input-a-regex-in-string-replace) – Joe Aug 29 '20 at 15:28

2 Answers2

1

Hello to change the name of the file using regex I would suggest using re.sub() function. See code below.

rootdir = ('C:\\Test')
pattern = re.compile(r'\w{3}\d{3}')

def removeChar():
    for filename in os.listdir(rootdir):
        new_name = re.sub(pattern=pattern,string=filename,repl='')
        
    
removeChar()

But that will only change the the string itself it won't change the name of the file. To do that you should probably use os.rename() function

import os

old_file_name = "/home/career_karma/raw_data.csv"
new_file_name = "/home/career_karma/old_data.csv"

os.rename(old_file_name, new_file_name)
Marcin
  • 302
  • 3
  • 11
0

You need to use os.rename(). Here is the full code:

import re
import os

rootdir = 'C:\\Test'
pattern = re.compile(r'\w{3}\d{3}')

def removeChar():
    for filename in os.listdir(rootdir):
        if pattern.match(filename) is not None:  # only rename files that match
          newName = re.sub(pattern, "", filename)
          newPath = os.path.join(rootdir, newName)
          oldPath = os.path.join(rootdir, filename)
          os.rename(oldPath, newPath)
    
removeChar()
Aziz Sonawalla
  • 2,482
  • 1
  • 5
  • 6