D35【python 接口自动化学习】- python基础之输入输出与文件操作

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)
总结
  1. 文件的读,写是实现文件合并的基础
  2. 通过遍历可以实现多个文件自动合并
相关推荐
claem1 分钟前
Mac端 Python脚本创建与理解
开发语言·python·macos
lixzest15 分钟前
目标检测算法应用工程师 面试高频题 + 标准答案
python·yolo·目标检测·计算机视觉
癫狂的兔子26 分钟前
【BUG】【Python】【Spider】Compound class names are not allowed.
开发语言·python·bug
木头左44 分钟前
基于Backtrader框架的指数期权备兑策略实现与验证
python
李松桃1 小时前
python第三次作业
java·前端·python
m0_561359671 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
马士兵教育1 小时前
计算机专业学生入行IT行业,编程语言如何选择?
java·开发语言·c++·人工智能·python
diediedei1 小时前
持续集成/持续部署(CI/CD) for Python
jvm·数据库·python
weixin_445402301 小时前
Python游戏中的碰撞检测实现
jvm·数据库·python