Python 如何检查并获取tempfolder中的最新文件(.xlsx)?

Python 如何检查并获取tempfolder中的最新文件(.xlsx)?,python,excel,python-3.x,Python,Excel,Python 3.x,这是一个复杂的问题… 运行Python时,我想确定临时文件夹(%USERPROFILE%\\AppData\\Local\\Temp\\)中最新的Excel文件,并将其复制到Windows上的D驱动器 我搜索了一些例子,但是没有 我怎样才能解决这个问题 这是下面的代码 import os import win32com.client as win32 import time import subprocess import tempfile dated_files = [(os.path.ge

这是一个复杂的问题…
运行Python时,我想确定临时文件夹(
%USERPROFILE%\\AppData\\Local\\Temp\\
)中最新的Excel文件,并将其复制到Windows上的
D
驱动器

我搜索了一些例子,但是没有

我怎样才能解决这个问题

这是下面的代码

import os
import win32com.client as win32
import time
import subprocess
import tempfile

dated_files = [(os.path.getmtime(fn), os.path.basename(fn)) for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]

dated_files.sort()
dated_files.reverse()

newest = dated_files[0][1]
print(newest)
=============================================================

Traceback (most recent call last):
File "D:/1002.py", line 11, in <module>
for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]
  File "D:/M1002.py", line 11, in <listcomp>

for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]
  File "C:\Python35\lib\genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'SampleCheck.xlsx'
Process finished with exit code 1
回溯(最近一次呼叫最后一次):
文件“D:/1002.py”,第11行,在
如果fn.lower().endswith('.xlsx')]
文件“D:/M1002.py”,第11行,在
如果fn.lower().endswith('.xlsx')]
getmtime中第55行的文件“C:\Python35\lib\genericpath.py”
返回os.stat(filename).st\u mtime
FileNotFoundError:[WinError 2]系统找不到指定的文件:“SampleCheck.xlsx”
进程已完成,退出代码为1

显然,在列表理解之前,您错过了
os.chdir(os.getenv('TEMP'))
。或者您应该执行
os.path.join(os.getenv('TEMP'),fn)
将其传递到
os.path.getmtime

详情如下:


getmtime
在当前工作目录中找不到文件
fn
。因此,您必须更改工作目录(使用
os.chdir
)或使用完整路径(例如由
os.path.join
构建)。

您自己尝试过实现吗?你能提供你最近的一次尝试吗?@idjaw当然我自己试了三天。。但我不知道…请出示你的代码。确保您满足提供@idjaw的标准。请参阅下面的代码,您是对的。我得到了正确的excel文件。谢谢你的帮助:)