简体   繁体   中英

Renaming all the files in folders within directory

Basically I have got it all done. But when actually trying to rename the files I get the error

Traceback (most recent call last):
  File 

    "C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav\sort_inner_wav.py", line 21, in <module>
        os.rename(file, new_name)
    FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Audio Track-10.wav' -> 'choman_10.wav'

Up until the last print statement the values are correct. Not sure how to rename it. Under wav folder there are 32 sub folder which has around 10 .wav files in it.

import os

rootdir = r'C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:

        filepath = subdir+os.sep+file
        if filepath.endswith('.wav'):

            f_name, f_ext=(os.path.splitext(file))

            if len(f_name) == 11:
              f_name = f_name+'-0'

            f_title,f_num =f_name.split('-')
            f_num=f_num.zfill(2)

            new_name = '{}_{}{}'.format('choman',f_num,f_ext)
            print (file, new_name)
            os.rename(file, new_name)

All you need is:

os.rename(filepath, subdir+os.sep+new_name)

That's because you need the full path.

If you are not running this script under the same location as 'rootdir' and there are sub directories, you need to specify the absolute path of source file and destination file. Otherwise, the file would not be found.

# python 2.7
os.rename(filepath, os.path.join(subdir, new_name))

# python >= 3.3
os.rename(file, new_name, subdir, subdir)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM