尝试重命名目录中的所有文件时出现FileNotFoundError

时间:2020-03-17 03:49:48

标签: python python-3.x file-not-found

我正在编写一个python脚本来重命名给定文件夹中的所有文件。 python脚本与j-l-classifier文件一起存在于我的images/jaguar中。我正在尝试运行以下脚本来获取文件夹中的每个文件,并将其重命名为以下格式:

jaguar_[#].jpg

但是它抛出以下错误:

Traceback (most recent call last):
  File "/home/onur/jaguar-leopard-classifier/file.py", line 14, in <module>
    main()
  File "/home/onur/jaguar-leopard-classifier/file.py", line 9, in main
    os.rename(filename, "Jaguar_" + str(x) + file_ext)
FileNotFoundError: [Errno 2] No such file or directory: '406.Black+Leopard+Best+Shot.jpg' -> 'Jaguar_0.jpg'

这是我的代码:

import os


def main():
    x = 0
    file_ext = ".jpg"

    for filename in os.listdir("images/jaguar"):
        os.rename(filename, "Jaguar_" + str(x) + file_ext)
        x += 1


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

os.listdir仅返回文件名(不返回文件路径...)

尝试以下

for filename in os.listdir("images/jaguar"):
    filepath = os.path.join("images/jaguar",filename)
    new_filepath = os.path.join("images/jaguar","Jaguar_{0}{1}".format(x,file_ext))
    os.rename(filepath, new_filepath)

露骨几乎总是通向更幸福生活的道路

答案 1 :(得分:1)

要使用os.rename(),您需要提供绝对路径。

我建议将第9行替换为os.rename(os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/{filename}"), os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/Jaguar_{str(x)}{file_ext}")

os.path.expanduser()允许您使用“〜”语法来辅助abs文件路径。

相关问题