# coding=gbk import os import os.path import natsort def GetFileList(dir, fileList): newDir = dir if os.path.isfile(dir): fileList.append(dir) elif os.path.isdir(dir): for s in os.listdir(dir): newDir = os.path.join(dir, s) GetFileList(newDir, fileList) return fileList fileDir = "" list = GetFileList(fileDir, []) contents = [] for i in list: with open(i, ‘r‘, encoding=‘utf-8‘) as f: if os.path.splitext(i)[1] == ‘.txt‘: content = f.read() contents.append(os.path.basename(i) + " " + "".join(content.split()) + "") contents = natsort.natsorted(contents) #print (contents) fo = open("label-sort.txt", "w") for line in contents: fo.writelines(line+"\n") fo.close()
参考https://www.cnblogs.com/xiaopanlyu/p/5905877.html
原文:https://www.cnblogs.com/nakkk/p/14678623.html