使用 Python 重命名目录中的多个文件 [英] Renaming multiple files in a directory using Python
本文介绍了使用 Python 重命名目录中的多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用此 Python 脚本重命名目录中的多个文件:
I'm trying to rename multiple files in a directory using this Python script:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(file, str(i)+'.jpg')
i = i+1
运行此脚本时,出现以下错误:
When I run this script, I get the following error:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(file, str(i)+'.jpg')
OSError: [Errno 2] No such file or directory
这是为什么?我该如何解决这个问题?
Why is that? How can I solve this issue?
谢谢.
推荐答案
重命名时你没有给出完整的路径,这样做:
You are not giving the whole path while renaming, do it like this:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join([str(index), '.jpg'])))
编辑:感谢 tavo,第一个解决方案是将文件移动到当前目录,修复了这个问题.
Edit: Thanks to tavo, The first solution would move the file to the current directory, fixed that.
这篇关于使用 Python 重命名目录中的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文