[英]Copy all files within directory into new directory while renaming files with same name in Python
[英]Renaming all the files in folders within directory
基本上我已经做好了。 但是当实际尝试重命名文件时,出现错误
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'
直到最后一个打印语句,值才正确。 不确定如何重命名。 在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)
所有你需要的是:
os.rename(filepath, subdir+os.sep+new_name)
那是因为您需要完整的路径。
如果不在与“ rootdir”相同的位置运行此脚本,并且有子目录,则需要指定源文件和目标文件的绝对路径。 否则,将找不到该文件。
# 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.