乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
28、批量实现txt文件内容合并

题目:

  在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)

posted on 2022-11-13 13:53  乐之之  阅读(293)  评论(0编辑  收藏  举报