How to change all file names in folder?

I have a folder that contains about 300 CSV files that have different names. I want to change all the file name to some new names:

my input files:

newAdress.csv
yourInformation.csv
countatnt.csv
.
.

I checked a few posts such as here but it's not saving in the format I want.

I tried to do as :

import glob, os
def rename(dir, pattern, titlePattern):
    print('pattern', pattern)
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename, 
                  os.path.join(dir, titlePattern % title + ext))

And then:

rename(r'/Users/Documnet/test', r'*.csv', r'file(%s)')

And i got:

file(newAdress).csv
file(yourInformation).csv
.

but it i need to save in the format of (newAdress.csv -> file1.csv, yourInformation.csv -> file2.csv):

file1.csv
file2.csv
file3.csv
.
.

1 answer

  • answered 2019-08-13 03:32 busybear

    You should change your for loop to something like this:

    for n, pathAndFilename in enumerate(glob.iglob(os.path.join(dir, pattern))):
        _, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename, os.path.join(dir, titlePattern.format(n+1)) + ext)
    

    But also you should call your function as (remove the parentheses):

    rename(r'/Users/Documnet/test', r'*.csv', r'file{}')
    

    Note I also changed the syntax since str.format is favored over the % syntax.