close

How to get the latest file in a folder?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get the latest file in a folder in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get the latest file in a folder?

  1. How to get the latest file in a folder?

    is quite incomplete code. What is files? It probably is a list of file names, coming out of os.listdir().

  2. get the latest file in a folder

    is quite incomplete code. What is files? It probably is a list of file names, coming out of os.listdir().

Method 1

Whatever is assigned to the files variable is incorrect. Use the following code.

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

Method 2

max(files, key = os.path.getctime)

is quite incomplete code. What is files? It probably is a list of file names, coming out of os.listdir().

But this list lists only the filename parts (a. k. a. “basenames”), because their path is common. In order to use it correctly, you have to combine it with the path leading to it (and used to obtain it).

Such as (untested):

def newest(path):
    files = os.listdir(path)
    paths = [os.path.join(path, basename) for basename in files]
    return max(paths, key=os.path.getctime)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read