Python gets all TXT files in the folder, generates new TXT with some content, and generates a list

Code detailed comments:

import os


file_name = []   # 创建一个空列表
for i in os.listdir('D:/fei/TXT'):   # 对目标文件夹进行逐一读取
    data_collect = ''.join(i)
    file_name.append(data_collect)   # 获取到的TXT文件放到列表中
# print(file_name)
for i in file_name:   # 对每一个TXT文件进行内容筛选
    fo = open('D:/feishu/TXT/' + f'{i}', 'r', encoding='UTF-8')  # 打开目标文件
    lines = fo.readlines()  #读取文件内容
    for lines in lines:  # 对TXT 进行逐行读取
        if 'arg' in lines:  # 获取带有‘arg’的那一行我们想要的内容
            a = lines.split()
            b = a[2]
            # print(b)
            path = "D:/fei/Monkey.txt"
            file = open(path, 'a')
            file.write(" " + b)   # 写入新的TXT
    file.write('\n')  # 重启一行

f = open(r'D:/fei/Monkey.txt', "rt")
a = [i for i in f]   # 转列表
price = [x.strip() for x in a if x.strip() != '']
print(price)
print(len(price))

operation result

 Convert each line to a list

There are several lines of content in the TXT file, and there are several data in the converted list

Guess you like

Origin blog.csdn.net/suixing6/article/details/128250088