python遍历制定目录下后缀为txt的文件并读取文件内容,并把内容新增添加到另一个目录下的keyrand.txt中并排重

次阅读

需求:遍历“D:/python/text/txt数据转移到另一个目录下的txt文件”目录下后缀为.txt的文件,读取文件内容,并将内容添加到“D:/python/text/txt数据转移到另一个目录下的txt文件/转移后/keyrand.txt”,并排除重复的内容:

import os

source_dir = "D:/python/text/txt数据转移到另一个目录下的txt文件"
target_file = "D:/python/text/txt数据转移到另一个目录下的txt文件/转移后/keyrand.txt"

# 创建一个空集合来存储文件内容,以排重
content_set = set()

# 读取现有文件内容,如果文件已存在
if os.path.exists(target_file):
    with open(target_file, "r", encoding="utf-8") as existing_file:
        existing_content = existing_file.read()
        content_set.update(existing_content.splitlines())

# 遍历目标目录下的所有.txt文件
for root, dirs, files in os.walk(source_dir):
    for file in files:
        if file.endswith(".txt"):
            file_path = os.path.join(root, file)
            with open(file_path, "r", encoding="utf-8") as source_file:
                content = source_file.read()
                content_set.update(content.splitlines())

# 打开目标文件,将内容写入并排重
with open(target_file, "w", encoding="utf-8") as target_file:
    for line in content_set:
        line = line.strip()  # 去掉首尾空白字符
        if line:  # 只写入非空行
            target_file.write(line + "\n")

print("文件内容已成功添加到目标文件并排重,同时去除空行。")


相关文章:

版权声明:由yongbin2023-10-23 21:29:50发表,共计1534字。
新手QQ群: 703975885,欢迎进群讨论 鲁班编程网