Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按mtime对列表中的文件进行排序,在列表中找不到文件_Python_Python 3.x - Fatal编程技术网

Python 按mtime对列表中的文件进行排序,在列表中找不到文件

Python 按mtime对列表中的文件进行排序,在列表中找不到文件,python,python-3.x,Python,Python 3.x,我正在尝试创建一个脚本,该脚本将自动将扫描的课堂讲稿从特定日期移动到一个文件夹中 为此,我需要按文件的上载日期排序,即文件的mdate 我遇到的问题是,脚本确实找到了文件并将其放入列表中,但是os.path.mtime()命令无法找到这些文件 这是我的密码: import os p="someDir" if os.path.isdir(p): files = os.listdir(p) print("Files found in folder:", files) file

我正在尝试创建一个脚本,该脚本将自动将扫描的课堂讲稿从特定日期移动到一个文件夹中

为此,我需要按文件的上载日期排序,即文件的
mdate

我遇到的问题是,脚本确实找到了文件并将其放入
列表中,但是
os.path.mtime()
命令无法找到这些文件

这是我的密码:

import os
p="someDir"
if os.path.isdir(p):
    files = os.listdir(p)
    print("Files found in folder:", files)
    files.sort(key=os.path.getmtime)
这就是我得到的错误:

Files found in folder: ['20180907.pdf', '20180831.pdf',
'20180905.pdf', '20180906.pdf']

Traceback (most recent call last):
File "/home/mats/Google Drive/Programmering/Python/Python 
Projects/homework/homework.py", line 32, in <module>
files.sort(key=os.path.getmtime)
File "/usr/lib/python3.6/genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [Errno 2] No such file or directory: '20180907.pdf'
文件夹:['20180907.pdf','20180831.pdf'中找到的
文件,
“20180905.pdf”、“20180906.pdf”]
回溯(最近一次呼叫最后一次):
文件“/home/mats/googledrive/Programmering/Python/Python
项目/作业/作业.py”,第32行,在
files.sort(key=os.path.getmtime)
文件“/usr/lib/python3.6/genericpath.py”,第55行,在getmtime中
返回os.stat(filename).st\u mtime
FileNotFoundError:[Errno 2]没有这样的文件或目录:“20180907.pdf”

您的变量文件包含:

['20180907.pdf', '20180831.pdf',
 '20180905.pdf', '20180906.pdf']
它不是相对于工作目录的绝对/相对路径。路径还包括文件夹

2种解决方案:1对包含路径名的列表进行排序,即:

from os.path import join
files = [join(p, elt) for elt in files]
或者更改循环中的工作目录,即代替打印:

os.chdir(p)

您好,欢迎光临!您可以将问题的代码部分括在反勾(`)中,使其看起来更漂亮。此外,您还应该编写代码,以便我们能够以最小的努力实际运行它:这样,我们就可以复制/粘贴代码,直接解决问题,而不必对您真正要问的问题进行胡乱猜测。我建议在您的问题中进行编辑以解决此问题。我尝试更改工作目录:if os.path.isdir(p):os.chdir(p)files=os.listdir(os.curdir)print(“文件夹中找到的文件:”,files)files.sort(key=os.path.getmtime),这给了我以下错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:“Anteckningar/20180831.pdf”@Mats,如果不可能测试它,这是我能做的最多的了。你需要了解自己。该错误明确指出传递到
os.path.getmtime
的路径不存在。试着先打印出来,在文件上打个圈。也许你会发现你的错误。请记住,此路径必须相对于由
os.chdir()
定义的工作目录进行定义。很抱歉,原来我是个白痴,您的解决方案有效,但这会导致一些其他问题,我所要做的就是在整理完文件后将工作目录更改回os.pardir,谢谢您的帮助