python提取当前目录中的多个文件中的内容合并写入到新的文件夹
以下是一个示例代码,可以将当前目录中所有以“.txt”结尾的文件的内容合并写入到一个新文件夹中的“merged.txt”文件中。
import os
# 获取当前目录
current_dir = os.getcwd()
# 创建新文件夹
new_folder = "merged_files"
if not os.path.exists(new_folder):
os.makedirs(new_folder)
# 合并文件
merged_file = open(os.path.join(new_folder, "merged.txt"), "w")
for file_name in os.listdir(current_dir):
if file_name.endswith(".txt"):
file_path = os.path.join(current_dir, file_name)
with open(file_path, "r") as file:
content = file.read()
merged_file.write(content)
merged_file.write("\n")
merged_file.close()
该代码首先获取当前目录,然后创建一个名为“merged_files”的新文件夹。接着,它遍历当前目录中的每个文件,如果文件名以“.txt”结尾,则打开该文件并将其内容写入到新文件夹中的“merged.txt”文件中。最后,关闭合并文件
原文地址: https://www.cveoy.top/t/topic/c8Qy 著作权归作者所有。请勿转载和采集!