Search code examples
pythonsortingfilenames

sort dated and monthed filenames chronologically


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)

Solution

  • 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']