【问题标题】:FileNotFoundError when trying to rename all the files in a directory尝试重命名目录中的所有文件时出现 FileNotFoundError
【发布时间】:2020-03-17 03:49:48
【问题描述】:

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

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()

【问题讨论】:

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


    【解决方案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 文件路径。

    【讨论】:

    • 这只是删除了所有文件
    • 真的很抱歉。它实际上已移至树中最高的文件夹。我忘了在 os.rename() 中为第二个 arg 放置一个 abs 文件路径,我的错。现在编辑它,它应该工作。 :)
    • 谢谢伙计。我已接受并赞成您的回答。如果您认为这是一个很好的问题,您能否也给我一个赞成票?
    【解决方案2】:

    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)
    

    直言不讳几乎总是通往更幸福生活的途径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2015-02-28
      相关资源
      最近更新 更多