![](/img/trans.png)
[英]how to rename files in a folder with the files name in file.txt in python?
[英]How to sort files in a folder with file name in 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', ...]
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.