day35 文件合并
学习日期:20241012
学习目标:输入输出与文件操作﹣-47 如何使用python合并多个文件?
学习笔记:
合并文件需求分析

合并两个文件

代码实现
python
# 合并两个文件
with open('demo1.txt') as f1:
file_data_1=f1.read()
with open('demo2.txt') as f2:
file_data_2=f2.read()
#将demo1和demo2的文件写入到demo3
with open('demo3.txt',mode='w') as f3:
f3.write(file_data_1)
f3.write(file_data_2)
遍历多个文件

代码实现
python
# 合并多个文件
file_name=['demo1.txt','demo2.txt','demo3.txt']
file_data=[]
for f_name in file_name:
with open(f_name) as f:
file_data.append(f.read())
with open('demo4.txt',mode='w') as f:
for data in file_data:
f.write(data)
总结
- 文件的读,写是实现文件合并的基础
- 通过遍历可以实现多个文件自动合并