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

时间:2016-09-23 01:24:37

标签: 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.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

1 个答案:

答案 0 :(得分:1)

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

更多细节:

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