python 合并指定目录下的多个txt文件
时间: 2023-09-12 09:02:43 浏览: 104
可以使用Python中的os和shutil模块来实现目录下多个txt文件的合并。具体步骤如下:
1. 导入os和shutil模块:
```
import os
import shutil
```
2. 获取指定目录下的所有txt文件:
```
dir_path = '指定目录路径'
txt_files = [f for f in os.listdir(dir_path) if f.endswith('.txt')]
```
3. 按照文件名的顺序排序txt_files列表:
```
txt_files.sort()
```
4. 创建一个新的txt文件,用于存储合并后的结果:
```
result_file = open('合并后的文件名.txt', 'w', encoding='utf-8')
```
5. 循环遍历txt_files列表,将每个txt文件的内容逐行写入result_file中:
```
for file_name in txt_files:
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
result_file.write(line)
```
6. 关闭result_file文件:
```
result_file.close()
```
完整代码如下:
```
import os
import shutil
dir_path = '指定目录路径'
txt_files = [f for f in os.listdir(dir_path) if f.endswith('.txt')]
txt_files.sort()
result_file = open('合并后的文件名.txt', 'w', encoding='utf-8')
for file_name in txt_files:
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
result_file.write(line)
result_file.close()
```
阅读全文