简体   繁体   中英

Python sort by date - specific file names

I have file names listed in a text file that looks like:

 20160703_042628_b.dat
 20160705_034207_b.dat
 20160706_035020_b.dat
 20160707_032630_b.dat
 20160708_042912_b.dat
 20160709_033232_b.dat
 20160710_034220_b.dat

How can i sort them by date and just extract the newest one?

This will extract the names of all the files with .dat extension and sort them by names and return the first value (recent date).

import os
dat_files = filter(lambda x: x.endswith('.dat'), os.listdir('mydir'))
dat_files.sort()
dat_files[0]

If you are receiving the file names in text file, the code below would work.

f = open('dates.txt', 'r')
x = f.readlines()
x.sort()
x[0]
import os
files = []
for file in os.listdir("/path/to/files/"):
  if file.endswith(".dat"):
    files.append(file)
sorted(files, reverse=True)[0]

You need to reverse the sort to pop the latest file.

If you don't have access to the system, and only have a the list of files printed in a file, read and split entries into a list:

with open('list_of_files.txt','r') as f:
    file = f.read().splitlines()
sorted(file, reverse=True)[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM