0

I have a Python (3.7) script that grabs a list of all files in a directory and goes through them in a for loop.

What I want to do is make sure only XML files are listed and the list of files is ordered either by creation date/time or by the number in a file name.

Currently using:

files = [f for f in os.listdir(self.config['report_directory']) if os.path.isfile(os.path.join(self.config['report_directory'], f))]

The above works fine for getting a list of files in a directory but I haven't been able to get it to list by file creation date or by the number in a file name.

Filenames example:

log_2983_report.xml
log_3948_report.xml
log_2198_report.xml

Any suggestions/help appreciated.

llanato
  • 2,508
  • 6
  • 37
  • 59

1 Answers1

1

I have replaced your self.config(...) with dir, so I can check it in my environment.

for sorting according to the number in the XML file name, you can sort using the sorted method with optional key parameter to sort according to the number in the file name/create/modification time.

import os

dir = os.path.dirname(os.path.abspath(__file__))
files = sorted([f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f)) and f.endswith('.xml')],
               key=lambda x: int(x.split('_')[1]))

print(files)

similarly, you can sort with the key to be the modification/creation time of the file, os.path.getmtime or os.path.getctime. for full explanation of how you can extract these details in the correct way for your OS, see:

How to get file creation & modification date/times in Python?

nonamer92
  • 1,887
  • 1
  • 13
  • 24