2016-09-23 96 views
-1

这是一个复杂的问题...
当我运行Python时,我想确定临时文件夹中的最新Excel文件(%USERPROFILE%\\AppData\\Local\\Temp\\)并将其复制到Windows上的D驱动器。如何检查并获取临时文件夹中的最新文件(.xlsx)?

我搜索的例子,但没有发现任何...

我怎样才能解决这个问题?

这是下面的代码...

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 
+0

你有没有试图自己实现呢?你能请你提供一个你最近尝试的[mcve]吗? – idjaw

+0

@idjaw 当然我自己尝试了3天.. 但是没有任何想法... – everline

+1

请显示您的代码。确保您符合提供[mcve] – idjaw

回答

1

很明显,你的列表理解之前错过os.chdir(os.getenv('TEMP'))。或者你应该做os.path.join(os.getenv('TEMP'), fn)将它传递到os.path.getmtime

在更多的细节:

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

+0

是的,您是对的。我有正确的excel文件。 谢谢你的帮助:) – everline

相关问题