读取文件夹中以.txt结尾的文件,将文件名写入txt并排序

# 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

posted @ 2021-04-19 20:50  Nakkk  阅读(421)  评论(0编辑  收藏  举报