我想重命名文件夹中的所有文件。每个文件名将从“whateverName.whateverExt”更改为“namepre + i.whateverExt”。例如从“xxxxx.jpg”到“namepre1.jpg”
我尝试从(Rename files in sub directories)修改代码,但失败了......
import os
target_dir = "/Users/usename/dirctectory/"
for path, dirs, files in os.walk(target_dir):
for i in range(len(files)):
filename, ext = os.path.splitext(files[i])
newname_pre = 'newname_pre'
new_file = newname_pre + str(i) + ext
old_filepath = os.path.join(path, file)
new_filepath = os.path.join(path, new_file)
os.rename(old_filepath, new_filepath)
有人能帮助我吗? THX !!!
答案 0 :(得分:1)
可能你在命名一些变量时犯了一些错误,试试这个:
import os
target_dir = "/Users/usename/dirctectory/"
newname_tmpl = 'newname_pre{0}{1}'
for path, dirs, files in os.walk(target_dir):
for i, file in enumerate(files):
filename, ext = os.path.splitext(file)
new_file = newname_tmpl.format(i, ext)
old_filepath = os.path.join(path, file)
new_filepath = os.path.join(path, new_file)
os.rename(old_filepath, new_filepath)
答案 1 :(得分:1)
试试这个版本:
import os
target_dir = "/Users/usename/dirctectory/"
for path, dirs, files in os.walk(target_dir):
for i in range(len(files)):
filename, ext = os.path.splitext(files[i])
newname_pre = 'newname_pre'
new_file = newname_pre + str(i) + ext
old_filepath = os.path.join(path, files[i]) # here was the problem
new_filepath = os.path.join(path, new_file)
os.rename(old_filepath, new_filepath)
答案 2 :(得分:0)
你应该更新这个问题,说明你运行它时会得到什么输出。此外,尝试在每次迭代时打印出new_file
的值,以查看是否获得了正确的文件路径。我的猜测是这一行:
new_file = newname_pre + str(i) + ext
......应该这样说:
new_file = newname_pre + str(i) + '.' + ext
......或者,用稍微更多的Pythonic语法:
new_file = "%s%i.%s" % (newname_pre, i, ext)