在python中使用with打开多个文件的方法
作者:忆向Blog 时间:2023-05-03 16:33:45
虽然初恋是java, 可是最近是越来越喜欢python,所以决定追根溯源好好了解下python的原理,架构等等.小脑袋瓜不太好使,只能记录下慢慢进步吧
使用with打开文件的好处不多说,这里记录一下如果要打开多个文件,该怎么书写简捷的代码。
场景是同时打开三个文件,文件行数一样,程序实现每个文件依次读取一行,同时输出。 首先来一种比较容易想到的写法,如下一样嵌套:
with open('file1') as f1:
with open('file2') as f2:
with open('file3') as f3:
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
注意,这里只能对一个文件进行for循环读取,不能写成:
for i,j,k in f1,f2,f3:
print(i,j,k)
这么多层缩进太恶心了,还是来一种简洁些的写法:
with open('file1') as f1, open('file2') as f2, open('file3') as f3:
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
还有一种优雅一点的写法:
from contextlib import nested #这个包是python2中的,不使用python3
with nested(open('file1'), open('file2'), open('file3')) as (f1,f2,f3):
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
来源:https://www.hustyx.com/python/119/
标签:python,with,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
判断sql语句执行是否成功
2008-07-05 12:22:00
Golang学习笔记之安装Go1.15版本(win/linux/macos/docker安装)
2024-05-13 10:41:23
在vue中动态添加class类进行显示隐藏实例
2024-05-09 15:13:28
![](https://img.aspxhome.com/file/2023/7/126547_0s.jpg)
Python中collections.Counter()的具体使用
2023-04-22 23:26:35
JavaScript使用canvas实现flappy bird全流程详解
2024-04-18 09:34:49
![](https://img.aspxhome.com/file/2023/2/136442_0s.gif)
Go WaitGroup及Cond底层实现原理
2024-02-18 23:05:03
![](https://img.aspxhome.com/file/2023/4/109734_0s.jpg)
一文详解CNN 解决 Flowers 图像分类任务
2023-02-28 22:23:39
![](https://img.aspxhome.com/file/2023/6/65876_0s.jpg)
在Python中使用Neo4j数据库的教程
2024-01-15 00:40:54
![](https://img.aspxhome.com/file/2023/3/134873_0s.jpg)
python概率计算器实例分析
2021-01-16 05:34:52
MS Server和Oracle中对NULL处理的一些细节差异
2009-06-10 17:35:00
FFrpc python客户端lib使用解析
2023-09-06 00:12:20
python读取图片任意范围区域
2023-07-16 06:26:21
![](https://img.aspxhome.com/file/2023/3/95193_0s.jpg)
python3结合openpyxl库实现excel操作的实例代码
2021-02-24 05:06:59
针对Sqlserver大数据量插入速度慢或丢失数据的解决方法
2024-01-21 02:54:46
python中的np.argmax() 返回最大值索引号
2022-08-07 14:22:57
![](https://img.aspxhome.com/file/2023/0/67860_0s.png)
Python面向对象之继承代码详解
2022-03-11 03:04:24
Python简易版图书管理系统
2022-06-07 21:11:10
Python使用progressbar模块实现的显示进度条功能
2023-11-20 05:40:07
python实现五子棋算法
2022-12-22 18:53:15
![](https://img.aspxhome.com/file/2023/4/133444_0s.gif)
python-图片流传输的思路及示例(url转换二维码)
2021-06-18 14:48:44