2

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
.
.
SethMMorton
  • 45,752
  • 12
  • 65
  • 86
Bilgin
  • 499
  • 1
  • 10
  • 25
  • 1
    See https://stackoverflow.com/questions/22171558/what-does-enumerate-mean/22171593 – Selcuk Aug 13 '19 at 03:18
  • I think i need to add something like {i} at the end of ```file(%s)..```which enumerates from ```1``` to ```length of the folder``` but i am not sure how to do ir – Bilgin Aug 13 '19 at 03:24

1 Answers1

0

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.

busybear
  • 10,194
  • 1
  • 25
  • 42