python open 打开多个文件,with 上下文管理器


有时候在编写程序的时候有需求要同时打开多个文件,这几个文件可能是经由原来某个文件拆分,分别进行一些处理后希望合并,此时需要同时打开这些文件并读取。通常Python中打开文本使用的是with语句,比如打开一个文件并读取每一行

Python
<span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/with" title="View all posts in with" target="_blank">with</a></span> open(filename) as fp: for line in fp: # do something
1
2
3
with open ( filename ) as fp :
     for line in fp :
         # do something

为了同时读取多个文件,可以使用下面的代码

Python
with open(filename1) as fp1, open(filename2) as fp2, open(filename3) as fp3: for l1 in fp1: l2 = fp2.readline() l3 = fp3.readline() # do something
1
2
3
4
5
with open ( filename1 ) as fp1 , open ( filename2 ) as fp2 , open ( filename3 ) as fp3 :
     for l1 in fp1 :
         l2 = fp2 . readline ( )
         l3 = fp3 . readline ( )
         # do something

contextlib.nested()

nested的汉语意思是“嵌套的,内装的”,从字面上读者也可能理解了,这个方法跟嵌套有关。前面有一个示例,是从一个文件读取,然后写入到另外一个文件。我不知道读者是否想过可以这么写:

Python
with open("23501.txt") as read_file: with open("23503.txt", "w") as write_file: for line in read_file.readlines(): write_file.write(line)
1
2
3
4
with open ( "23501.txt" ) as read _file:
     with open ( "23503.txt" , "w" ) as write_file :
         for line in read_file . readlines ( ) :
             write_file . write ( line )

此种写法不是不行,但是不提倡,因为它太不Pythoner了。其实这里就涉及到了嵌套,因此可以使用contextlib.nested重写。

Python
with <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/contextlib" title="View all posts in contextlib" target="_blank">contextlib</a></span>.nested(open("23501.txt", "r"), open("23503.txt", "w")) as (read_file, write_file): for line in read_file.readlines(): write_file.write(line)
1
2
3
with contextlib . nested ( open ( "23501.txt" , "r" ) , open ( "23503.txt" , "w" ) ) as ( read_file , write_file ) :
     for line in read_file . readlines ( ) :
         write_file . write ( line )

这是一种不错的写法,当然,在本节最前面所用到的写法,也是可以的,只要不用刚才那种嵌套。

拓展: 上下文管理器是支持上下文管理协议的对象,这种对象实现了__enter__()和__exit__()方法。

为了解把这个问题解释清楚,需要先做点别的操作,虽然工程中一般不需要做。

Python
#!/usr/bin/env <span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span> # coding=utf-8 class ContextManagerOpenDemo(object): def __enter__(self): print "Starting the Manager." #Python 3: print("Starting the Manager.") def __exit__(self, *others): print "Exiting the Manager." #Python 3: print("Exiting the Manager.") with ContextManagerOpenDemo(): print "In the Manager." #Python 3: print("In the Manager.")
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# coding=utf-8
 
class ContextManagerOpenDemo ( object ) :
 
     def __enter__ ( self ) :
         print "Starting the Manager."          #Python 3: print("Starting the Manager.")
 
     def __exit__ ( self , * others ) :
         print "Exiting the Manager."              #Python 3: print("Exiting the Manager.")
 
with ContextManagerOpenDemo ( ) :
     print "In the Manager."          #Python 3: print("In the Manager.")

在上面的代码示例中,我们写了一个类ContextManagerOpenDemo(),你就把它理解为我自己写的Open()吧,当然使最简版本了。在这个类中,__enter__()方法和__exit__()方法都比较简单,就是要检测是否执行该方法。
然后用with语句来执行,目的是按照“上下文管理器”的解释那样,应该首先执行类中的__enter__()方法,它总是在进入代码块前被调用的,接着就执行代码块——with语句下面的内容,当代码块执行完毕,离开的时候又调用类中的__exit__()。
检验一下,是否按照上述理想路径执行。

Python
$ <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/python" title="View all posts in python" target="_blank">python</a></span> 23502.py Starting the Manager. In the Manager. Exiting the Manager.
1
2
3
4
$ python 23502.py
Starting the Manager .
In the Manager .
Exiting the Manager .



  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值