How to check and get the newest file(.xlsx) in a tempfolder?
<p>Here is a complicated problem...<br>
When I run Python, I want to determine the newest Excel file in temporary folder (<code>%USERPROFILE%\\AppData\\Local\\Temp\\</code>) and copy it to the <code>D</code> drive on Windows.</p>

<p>I searched for examples but there weren't any...</p>

<p>How can I solve this problem?</p>

<p>This is the code below...</p>

<pre><code>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)
</code></pre>

<p>=============================================================</p>

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

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
</code></pre>

<p>Obviously you missed <code>os.chdir(os.getenv('TEMP'))</code> before the list comprehension. Or you should do <code>os.path.join(os.getenv('TEMP'), fn)</code> to pass it into <code>os.path.getmtime</code>.</p>

<p>In more details:</p>

<p><code>getmtime</code> cannot find the file <code>fn</code> in the current working directory. So you have to change the working dir (with <code>os.chdir</code>) or to use the full path (constructed by <code>os.path.join</code> for example).</p>

python excel python-3.x