找不到文件错误 python [重复]

2024-01-09

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)被添加到混合物中。

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

为什么引用文件时会出现错误,按名称显示无法找到该文件,我该如何解决此问题?


Your files变量是文件名only,不是完整的路径。因此它会在你的当前工作目录,不在哪里listdir找到了。

以下代码将使用full路径名称:

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

The os.path.join()联合起来folder and file给你一个full路径规范。例如,os.path.join("/temp","junk.txt")会给你/temp/junk.txt(在 UNIX 下)。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

找不到文件错误 python [重复] 的相关文章

随机推荐