import os
# 读取txt文件名
def load():
names = os.listdir(r'C:\\Users\\86131\\Desktop\\合成txt\\') # 读取文件夹内所有文件名
txt_names = [] # 以列表的形式储存
for name in names:
if name.split('.')[-1] == 'txt': # 只记录txt文件名
txt_names.append(name)
return txt_names
txt_names = load()
content = '检测到' + str(len(txt_names)) + '个txt文件:\n\n' # content记录内容
for txt_name in txt_names:
with open(r'C:\\Users\\86131\\Desktop\\合成txt\\' + txt_name, 'r', encoding='utf-8') as file:
content = content + txt_name + ':\n' + file.read() + '\n\n'
file.close()
with open('result.txt', 'a', encoding='utf-8') as file: # 将content记录到result.txt中
file.write(content)
file.close()
运行结果:
使用时,将文件夹路径复制到names = os.listdir(r' ')和with open(r' ' + txt_name, 'r', encoding='utf-8') as file:中。而with open('result.txt', 'a', encoding='utf-8') as file:中的路径也可以选择自己更改,不一定非要保存到代码文件的根目录中。
注意:在复制文件夹路径的时候,要多加一个‘\',否则'\'会被python当成转义符。例如:复制的是C:\Users\86131\Desktop\合成txt\,那要更改成C:\\Users\\86131\\Desktop\\合成txt\\。