import os
path = "D:\HY_22\PycharmProjects\data-ap10" #文件夹目录
files= os.listdir(path) #得到文件夹下的所有文件名称
txts = []
a = []
for file in files: #遍历文件夹
position = path+'\\'+ file #构造绝对路径,"\\",其中一个'\'为转义符
print (position)
with open(position,encoding='utf-8',errors='ignore') as f: #打开文件
data = f.read() #读取文件
for j in data.split('\n'):
if j not in a:
a.append(j)
txts.append(data)
txts = ','.join(txts)#转化为非数组类型
print (txts)
b='D:\HY_22\PycharmProjects\shaixuan_ap10.txt'
file = open(b, 'w',encoding='utf-8')
for line in a:
file.write(line+'\n')
file.close()
print("保存文件成功")
参考:(17条消息) python 批量读取文件夹中的多个TXT文件_阿优乐扬的博客-CSDN博客_python读取多个txt文件