2016-09-23 100 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

相關問題