Home > Software design >  Sort files in folder based on date and time with Python
Sort files in folder based on date and time with Python

Time:01-05

I am trying to loop through all json files in a directory and append their data to my dictionary. It seems as the appending is random and not sorted by date and time, as the files are sorted. Is there anyway to loop and sort the files based on their filename?

I have tried other solutions such as adding 'time': datetime.fromtimestamp(os.path.getmtime(file_path)) to json_files and then sorting it with json_files.sort(key=lambda x: x['time']). The issue is that it is using last modified, and it doesn't seem reliable at all.

Example files

data/41/2022-12-06 10:39:16.124069.json
data/41/2022-12-06 16:14:19.285462.json
data/41/2022-12-06 10:30:23.831559.json

My code

dir_path = 'data/41'

for file_name in os.listdir(dir_path):
    json_files = []
    file_path = os.path.join(dir_path, file_name)
    with open(file_path, 'r') as json_file:
        try:
            json_data = json.load(json_file)

            # Add the JSON data and the file modified time to the list
            json_files.append({
                'json': json_data
            })
        except:
            pass

CodePudding user response:

Well, if I understand you correctly, this little trick will give you the desired behaviour:

dir_path = 'data/41'

# notice this `sorted` thing
for file_name in sorted(os.listdir(dir_path)):
    json_files = []
    file_path = os.path.join(dir_path, file_name)
    with open(file_path, 'r') as json_file:
        try:
            json_data = json.load(json_file)

            # Add the JSON data and the file modified time to the list
            json_files.append({
                'json': json_data
            })
        except:
            pass
  • Related