题目:
在many_org文件夹中有三个.txt文件,如何将三个文件的内容整理到一个文件里?
思路:
1、遍历路径下的所有文件。
2、判断出.txt文件,将其所有内容保存至新列表内。
3、新建文件,保存。
结果:
import os
insert_dir = "../28批量实现txt文件内容合并/many_arg"
contents=[]
for file in os.listdir(insert_dir):
file_path = f"{insert_dir}/{file}"
if os.path.isfile(file_path) and file.endswith(".txt"):
with open(f"{file_path}",'r',encoding="utf-8") as f:
contents.append(f.read())
file_contents= "\n".join(contents)
print(file_contents)
with open("new_file.txt",'w',encoding='utf-8') as fi:
fi.write(file_contents)
标签:文件,批量,28,file,path,txt,contents
From: https://www.cnblogs.com/LoLong/p/16885881.html