文件Folder下有file1.txt、file2.txt和folder1文件夹,folder1文件夹下有file3.txt、file4.txt两个文件,遍历Folder文件夹下所有文件,将文本文件内容合并生成一个新的文本文件merge.txt存放在Folder文件夹中,不破坏原始文件
时间: 2024-02-06 15:10:09 浏览: 104
合并文件夹内的所有txt文本文件为一个txt文件
好的,以下是Python代码实现:
```python
import os
# 遍历文件夹并将文本文件内容合并
def merge_files(folder_path, merge_file_path):
with open(merge_file_path, 'w', encoding='utf-8') as merge_file:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
if file_path.endswith('.txt'):
with open(file_path, 'r', encoding='utf-8') as f:
merge_file.write(f.read())
# 测试
folder_path = './Folder'
merge_file_path = './Folder/merge.txt'
merge_files(folder_path, merge_file_path)
```
这段代码定义了一个`merge_files`函数,它接受两个参数:`folder_path`为要遍历的文件夹路径,`merge_file_path`为生成的合并文本文件的路径。函数使用`os.walk`函数遍历文件夹,对于每个文本文件,它将其内容读取并写入到合并文本文件中。最后调用`merge_files`函数即可完成操作。
阅读全文