Opening the newest file inside a specific folder

Viewed 63

I want the open a txt file.

There is a lot of .txt files in a folder on the desktop and they are always increasing.

I want to open the newest of these txt files.

with open(file=f"C:\\Users\\selman\Desktop\\simpleFolder\\NEWEST.txt", mode="r") as file:

txt file names:

mmnhodja_Sat Mar 12 22;00;24 2022.txt

mmnhodja_Sat Mar 12 22;02;12 2022.txt

mmnhodja_Sat Mar 12 22;04;22 2022.txt

mmnhodja_Sat Mar 12 22;06;33 2022.txt

mmnhodja_Sat Mar 12 22;08;57 2022.txt

going like that.

3 Answers

You can use file stat to find creation/modification/access time:

import datetime as dt
from pathlib import Path


curr_dir = Path('.')
text_files = list(curr_dir.glob('*.txt'))
# sort by modification time (st_mtime) in reversed order
newest_file = sorted(
    [(f, dt.datetime.fromtimestamp(f.stat().st_mtime)) for f in text_files],
    key=lambda item: item[1], reverse=True
)[0][0]
print(newest_file)
import os
import os.path
import glob

os.chdir("directory") # put your Desktop directory here

files = glob.glob(directory + "*.txt") # this is to find all txt files

# If you want to find the files that were last modified
newest_files = sorted(files, key = lambda x: os.path.getmtime(x), reverse=1)

# if you want to find the files that were last created
newest_files = sorted(files, key = lambda x: os.path.getctime(x), reverse=1)

the newest_files list is a list with all files sorted from newest to oldest. If you want to also include other files then change the "*.txt" to something else.

import os
import glob

os.chdir(os.getcwd())
files = sorted(glob.glob("*.txt"), key=os.path.getmtime)

print(files[-1])
Related