如何在python中使用文件名对文件夹中的文件进行排序

2024-10-02 10:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对一些扩展名为.sim的模拟文件进行排序。目前,我有以下代码:

import os
import re


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

print(files) 

当我运行代码时,会得到以下结果:

['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', ...]

Tags: 文件代码importrefor排序osfiles
1条回答
网友
1楼 · 发布于 2024-10-02 10:31:17
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

相关问题 更多 >

    热门问题