Rename files in a folder using python

Viewed 31

I have different docs,pdf files available in my folder (almost 1000 no). I want to rename all the files. My folder structure like -

nikita
  ----------abc.doc
  ----------des.doc
  ----------jj1.pdf

I want name should be starting with NC_. For example

nikita
  ----------NC1_abc.doc
  ----------NC2_des.doc
  ----------NC3_jj1.pdf

I have done the following code -

import os
import glob
import pandas as pd

os.chdir('C:\\Users\\EVM\\Nikita\\')
print(os.getcwd())

for count, f in enumerate(os.listdir()):
    f_name, f_ext = os.path.splitext(f)
    f_name = "NC" + str(count) + '_' + f_name
    new_name = f'{f_name}{f_ext}'
    os.rename(f, new_name)

But my output starts with NC0 not NC1.

nikita
  ----------NC0_abc.doc
  ----------NC1_des.doc
  ----------NC2_jj1.pdf
1 Answers

the enumerate function accepts an optional argument to declare the index you want to start with. Click here for further information.

So if you added the argument like this:

enumerate(os.listdir(), 1)

the output should start with NC1.

Related