Home > Software design >  Renaming characters in multiple files in a folder
Renaming characters in multiple files in a folder

Time:12-16

I'm trying to rename files in a folder with import os. Folder

I want to replace the 'SN' in all these files with 'NG'.

I have tried with the code `

filenames = os.listdir(serial_dir) #serial_dir is the right path
for filename in filenames:
            dst = filename.replace('SN', 'NG')
            os.rename(filename, dst)

` I have tested by printing out "filenames" and get the return:

['SN0000244,calibrationCheck1.txt', 'SN0000244,calibrationCheck2.txt', 'SN0000244,CurrentCalibration1.csv', 'SN0000244,CurrentCalibration2.csv', 'SN0000244,CurrentCalibrationFit1.csv', 'SN0000244,CurrentCalibrationFit2.csv', 'SN0000244.txt']

But i get the error: can only concatenate str (not "int") to str

Thanks.

I tried searching stackoverflow for answers but got nothing.

CodePudding user response:

os.rename looks for files in the current directory, not in the directory you specified. You should add the directory path before the file name.

serial_dir = 'path/to/dir'
filenames = os.listdir(serial_dir)
for filename in filenames:
    dst = filename.replace('SN', 'NG')
    os.rename(f'{serial_dir}/{filename}', f'{serial_dir}/{dst}')
  • Related