简体   繁体   English

重命名目录中文件夹中的所有文件

[英]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. 在wav文件夹下,有32个子文件夹,其中约有10个.wav文件。

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. 如果不在与“ rootdir”相同的位置运行此脚本,并且有子目录,则需要指定源文件和目标文件的绝对路径。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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