python - 在 Python 中按创建日期排序文件列表时出现奇怪的错误

标签 python file sorting date

我一直在关注这个教程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/

相关文章:

python - 更多Pythonic/更好的方式来编写这个?

python - 将列表切片为最大字符串大小

python - 如何将父类方法的内容添加到子类方法中

c++ - 文件创建时间的 std::filesystem::last_write_time() 等价物在哪里?

php - 在php中获取文件的大小

javascript - 在javascript中按多个键和多个顺序排序

python - 从本地 linux 文件夹移动到使用 cifs 挂载的 windows 共享

Python:打开的文件太多错误

java - 如何使用二进制数技术对整数的数字进行排序?

javascript - 根据日期键对javascript对象进行排序