Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the file name which contains the latest timestamp in a directory using python

Lets say that in a directory i have multiple files like this:

Test1_2021-05-17 1139.xlsx
Test1_2021-04-17 1139.xlsx
Test1_2021-03-17 1139.xlsx
Test1_2021-02-17 1139.xlsx
Test1_2021-01-17 1139.xlsx
Test2_2021-05-17 1139.xlsx
Test2_2021-04-17 1139.xlsx
Test2_2021-03-17 1139.xlsx
Test2_2021-02-17 1139.xlsx

How can I find the file which contains the latest timestamp and then i want to open it as a data frame.

So, eg. o want to get the file name: Test1_2021-05-17 1139.xlsx. How can i do that with python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this one but it is not getting me the file with the latest timestamp on its name:

import glob
import os

list_of_files = glob.glob('/path/*') 
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

>Solution :

Maybe you have to filter your filenames before:

import pathlib
import os.path
import pandas as pd

filename = max([f for f in pathlib.Path('/path').glob('Test_*.xlsx')], 
               key=os.path.getctime)

df = pd.DataFrame(filename)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading