我一直在关注这个教程http://code.activestate.com/recipes/576804-find-the-oldest-or-yougest-of-a-list-of-files/将文件列表排序为创建日期。 但是,当我使用此代码运行脚本时:
import os
path = 'pages/'
files = sorted(os.listdir(path), key=os.path.getctime)
input(files)
...我收到此错误:
Traceback (most recent call last):
File "C:\ilmiont_server\blog\homepage.py", line 17, in <module>
files = sorted(os.listdir(path), key=os.path.getctime)
File "C:\Python33\lib\genericpath.py", line 64, in getctime
return os.stat(filename).st_ctime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'rsr.txt'
“rsr.txt”目前是我搜索的“pages”目录中的唯一文件。奇怪的是它在与脚本相同的目录中工作,并且如果“页面”目录为空。对于上下文,我要排序的“页面”文件夹比脚本所在的文件夹低一级。请帮助我了解出了什么问题!
提前致谢,Ilmiont。
最佳答案
os.path.getctime
找不到 os.listdir
返回的文件,因为 os.listdir
只返回它们的名称,而不是它们的路径。您需要为 os.path.getctime
提供文件路径。
以下应该适用于您的具体情况:
import os
path = 'pages/'
files = sorted(os.listdir(path), key=lambda x: os.path.getctime(path+x))
input(files)
但是,通常使用 os.path.join
更安全创建文件路径:
import os
path = 'pages/'
files = sorted(os.listdir(path), key=lambda x: os.path.getctime(os.path.join(path, x)))
input(files)
关于python - 在 Python 中按创建日期排序文件列表时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104155/