How to get the latest file in a folder using python
<p>i need to get the latest file of a folder using python. While using the code:</p>

<pre><code>max(files, key = os.path.getctime)
</code></pre>

<p>I am getting the below error:  </p>

<blockquote>
  <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p>
</blockquote>

<p>(Edited to improve answer)</p>

<p>First define a function get_latest_file</p>

<pre><code>def get_latest_file(path, *paths):
    fullpath = os.path.join(path, paths)
    ...
get_latest_file('example', 'files','randomtext011.*.txt')
</code></pre>

<p>You may also use a docstring !</p>

<pre><code>def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
</code></pre>

<p><strong>If you use Python 3</strong>, you can use <a href="https://docs.python.org/3/library/glob.html?highlight=glob.iglob#glob.iglob" rel="nofollow">iglob</a> instead.</p>

<p><strong>Complete code to return the name of latest file:</strong></p>

<pre><code>def get_latest_file(path, *paths):
    """Returns the name of the latest (most recent) file 
    of the joined path(s)"""
    fullpath = os.path.join(path, *paths)
    files = glob.glob(fullpath)  # You may use iglob in Python3
    if not files:                # I prefer using the negation
        return None                      # because it behaves like a shortcut
    latest_file = max(files, key=os.path.getctime)
    _, filename = os.path.split(latest_file)
    return filename
</code></pre>

python