我需要按文件名顺序来遍历 凝聚12月上_1 凝聚12月上_2 凝聚12月上_10 凝聚12月上_12 凝聚12月上_22用python
可以使用Python中的sorted()函数按照文件名顺序对文件进行排序,然后再进行遍历。示例代码如下:
import os
path = "your_directory_path"
files = os.listdir(path)
sorted_files = sorted(files, key=lambda x: int(x.split("_")[-1]))
for file in sorted_files:
# 进行文件操作
print(file)
其中,path为待遍历的目录路径,files为该目录下所有文件的文件名列表,sorted_files为按文件名顺序排序后的文件名列表。lambda函数用于按照文件名中的数字部分进行排序,int(x.split("")[-1])表示将文件名以""进行分割,并转换最后一部分为整数进行排序。最后,遍历sorted_files列表,即可按文件名顺序进行操作。
原文地址: https://www.cveoy.top/t/topic/CoG 著作权归作者所有。请勿转载和采集!