遍历查找含特定字符的文件并排序

abc_311_1.txt
abc_311_2.txt
abc_311_3.txt
abc_311_4.txt

 1 import os
 2 
 3 
 4 def getFiles(dir, suffix):
 5     res = []
 6     for root, directory, files in os.walk(dir):  # =>当前根,根下目录,目录下的文件
 7         for filename in files:
 8             name, suf = os.path.splitext(filename)  # =>文件名,文件后缀
 9             '''if suf == suffix:
10                 # res.append(os.path.join(root, filename))  # =>吧一串字符串组合成路径'''
11             if '_311_' in filename:
12                 res.append(filename)
13     return res
14 
15 
16 # 声明字典
17 key_value = {}
18 
19 for file in getFiles("D:/pyCode/tmp", '.txt'):
20     print(file)
21     print('file name:', os.path.splitext(file)[0])
22     print(os.path.splitext(file)[0].split('_', 2)[2])
23     num = int(os.path.splitext(file)[0].split('_', 2)[2])
24     # 初始化
25     key_value[num] = file
26 
27 print("按键(key)排序1:")
28 
29 # sorted(key_value) 返回一个迭代器
30 # 字典按键排序
31 for i in sorted(key_value):
32     print((i, key_value[i]), end=" ")
33 
34 print("
按键(key)排序2:")
35 
36 listFile = []
37 for i in sorted(key_value):
38     print(key_value[i])
39     listFile.append(key_value[i])
40 
41 for item in listFile:
42     print(item)
原文地址:https://www.cnblogs.com/mikew/p/12013506.html