1

I have several txt files with the format below. They are all in the same directory called folder_path, and all begin with the format "date Month 2019", followed by the rest of the file name then ".txt". Each file has a different name and a different date and month.

4 JUN 2019 file name something.txt
1 JUN 2019 file name something.txt
18 APR 2019 file name.txt
15 APR 2019 file name.txt
13 APR 2019 file name.txt

I need to order them in chronological order, in month and date, without changing the rest part of the filename. so the files should be like:

13 APR 2019 somename.txt
15 APR 2019 somename.txt
18 APR 2019 filename.txt
1 JUN 2019 somename.txt
4 JUN 2019 somename.txt

I am thinking about using sorted and count the first 7 digits, or to separate the date and month from the filenames. I did something like this, but nothing happened. I'm quite new to Python so appreciate any solutions.

def first_7chars(filename):
    return(filename[0:8])

sorted(folder_path, key = first_7chars)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Maibaozi
  • 47
  • 8
  • 1
    With `sorted(folder_path)`, if `folder_path` is a string, that'll sort the characters in the string itself, not the files inside the directory. So I added a duplicate link about how to get the filenames in a directory for you. – wjandrea Dec 31 '21 at 22:07

1 Answers1

3

You could use datetime.datetime in sorted function:

files = ['4 JUN 2019 file name something.txt',
'1 JUN 2019 file name something.txt',
'18 APR 2019 file name.txt',
'15 APR 2019 file name.txt',
'13 APR 2019 file name.txt']

from datetime import datetime
out = sorted(files, key=lambda file: datetime.strptime(' '.join(file.split()[:3]), '%d %b %Y'))

Output:

['13 APR 2019 file name.txt',
 '15 APR 2019 file name.txt',
 '18 APR 2019 file name.txt',
 '1 JUN 2019 file name something.txt',
 '4 JUN 2019 file name something.txt']
  • 2
    Oh nice, I didn't expect `%d` to work directly since the docs said `Day of the month as a zero-padded decimal number`. That saves trouble. – shriakhilc Dec 31 '21 at 21:56