How to get the Latest File in a Folder using Python
In this guide, you’ll see how to get the latest file in a folder using Python.
To start, here is a template that you may use to get the latest file:
import glob import os.path folder_path = r'path where your files are located' file_type = r'\*type' files = glob.glob(folder_path + file_type) max_file = max(files, key=os.path.getctime) print(max_file)
In the next section, you’ll see a simple example with the steps to get the latest file for a given folder.
Steps to get the Latest File in a Folder using Python
Step 1: Capture the Path where the files are stored
To begin, capture the path where your files are currently stored.
For example, let’s assume that 2 CSV files are stored in a ‘Test’ folder, where the path to the folder is:
C:\Users\Ron\Desktop\Test
The names, and the creation date, of the files, are as follows:
- First file, called Furniture, was created on 2020-01-09 8:04 PM
- Second file, called Products, was created 6 minutes later on 2020-01-09 8:10 PM
The ultimate goal is to get the latest file created. In this case, it would be the ‘Products’ file.
Step 2: Get the Latest File in the Folder using Python
You may now use this template to get the latest file in a folder using Python:
import glob import os.path folder_path = r'path where your files are located' file_type = r'\*type' files = glob.glob(folder_path + file_type) max_file = max(files, key=os.path.getctime) print(max_file)
In the context of our example:
- The path where the files are located is: C:\Users\Ron\Desktop\Test
- The file type is: CSV
So the complete Python code would look as follows (don’t forget to place the ‘r‘ character before your path to avoid any errors in the path name):
import glob import os.path folder_path = r'C:\Users\Ron\Desktop\Test' file_type = r'\*csv' files = glob.glob(folder_path + file_type) max_file = max(files, key=os.path.getctime) print(max_file)
C:\Users\Ron\Desktop\Test\Products.csv
What if you want to import the latest file into Python?
If that’s the case, you may proceed to step 3 below.
Step 3 (optional step): Import the Latest File into Python
You can use Pandas in order to import a CSV file into Python.
If you haven’t already done so, install the Pandas package. You may use this command to install Pandas under Windows:
Finally, apply the code below (adjusted to your path) in order to import the latest csv file:
import glob import os.path import pandas as pd folder_path = r'C:\Users\Ron\Desktop\Test' file_type = r'\*csv' files = glob.glob(folder_path + file_type) max_file = max(files, key=os.path.getctime) import_file = pd.read_csv(max_file) print(import_file)
You’ll then see the following data from the Products file:
product_id product_name price 0 1 Oven 800 1 2 Microwave 350 2 3 Toaster 80 3 4 Refrigerator 1100 4 5 Dishwasher 900