简体   繁体   中英

How to sort files in a folder with file name in python

I am trying to sort some simulation files with the extension.sim. At the moment I have the following code:

import os
import re


files = [f for f in os.listdir('.') if re.match(r'.*\.sim', f)]

print(files) 

When I run the code I get these results:

['Yunlin_Shorepull_South_Current_1.8_Wind_0.sim', 
'Yunlin_Shorepull_South_Current_1.8_Wind_0_Relocated.sim', 
'Yunlin_Shorepull_South_Current_1.8_Wind_1.sim', 
'Yunlin_Shorepull_South_Current_1.8_Wind_10.sim', 
'Yunlin_Shorepull_South_Current_1.8_Wind_10_Relocated.sim', 
'Yunlin_Shorepull_South_Current_1.8_Wind_11.sim', ...]
import os
import re

files = [f for f in os.listdir('.') if f.endswith(".sim")]
files = ['Prefix_0.sim',
         'Prefix_1.sim',
         'Prefix_0_Relocated.sim',
         'Prefix_10.sim',
         'Prefix_11.sim',
         'Prefix_1_Relocated.sim',
         'Prefix_2_Relocated.sim',
         'Prefix_2.sim',
         'Prefix_10_Relocated.sim',
         'Prefix_12.sim',
         'Prefix_12_Relocated.sim',
         'Prefix_11_Relocated.sim',
         ]

prefix = "Prefix_"
suffix = "_Relocated.sim"
number_regex = prefix + r"(\d+)"

def extract_number(s):
    match = re.match(number_regex, s)
    return int(match.group(1))

original_files = [f for f in files if not f.endswith(suffix)]
relocated_files = [f for f in files if f.endswith(suffix)]

sorted_files = sorted(original_files, key=extract_number) + \
               sorted(relocated_files, key=extract_number)

for f in sorted_files:
    print(f)

Prefix_0.sim
Prefix_1.sim
Prefix_2.sim
Prefix_10.sim
Prefix_11.sim
Prefix_12.sim
Prefix_0_Relocated.sim
Prefix_1_Relocated.sim
Prefix_2_Relocated.sim
Prefix_10_Relocated.sim
Prefix_11_Relocated.sim
Prefix_12_Relocated.sim

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