Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Renaming characters in multiple files in a folder

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
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading