【问题标题】:File not found error python [duplicate]找不到文件错误python [重复]
【发布时间】:2015-03-20 05:09:51
【问题描述】:
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
    if files.endswith(".torrent"):
        print(files + time.ctime(os.path.getatime(files)))

运行此脚本时出现文件未找到错误。 FileNotFoundError: [WinError 2] The system cannot find the file specified: 'TORRENT NAME.torrent'

time.ctime(os.path.getatime(files) 之前一切正常 被添加到混合物中。

我希望脚本显示“种子名称”“上次修改日期” 对于文件夹中的每个文件。

为什么错误引用了一个文件,按名称说它无法找到,我该如何解决这个问题?

【问题讨论】:

    标签: python


    【解决方案1】:

    您的files 变量只是文件名, 不是完整路径。因此它将在您的当前工作目录中寻找它,而不是在listdir 找到它的地方。

    以下代码将使用完整的路径名:

    import os
    import time
    folder = r'C:\users\chris\desktop\torrent'
    files = os.listdir(folder)
    for file in files:
        if file.endswith(".torrent"):
            print(file + " " + time.ctime(os.path.getatime(os.path.join(folder,file))))
    

    os.path.join() 结合了folderfile,为您提供完整 路径规范。例如,os.path.join("/temp","junk.txt") 将给您/temp/junk.txt(在 UNIX 下)。

    然后它以与您尝试仅使用 file 变量完全相同的方式使用它,获取最后访问时间并以可读方式对其进行格式化。

    【讨论】:

    • 我对 python 还很陌生,你能解释一下这个魔法是如何工作的吗time.ctime(os.path.getatime(os.path.join(folder,file)))
    • @Cs142,我会在答案中添加更多内容,而不是在评论中回答。
    【解决方案2】:

    它需要绝对的path

    os.path.getatime(路径)

    返回最后一次访问路径的时间。

    所以,open('xxx.torrent') 将不起作用。

    改为使用open('C:\users\chris\desktop\torrents\xxx.torrent')

    import os
    import time
    torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
    for files in torrent_folder:
        if files.endswith(".torrent"):
            filepath = os.path.join('C:\users\chris\desktop\torrents',files)
            print(files + time.ctime(os.path.getatime(filepath)))
    

    【讨论】:

    • Aaron,torrent_folder 是一个列表,您可能希望在 os.path.join() 调用中使用原始 路径
    • @paxdiablo 感谢您的纠正。我修改了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    相关资源
    最近更新 更多