有时候在编写程序的时候有需求要同时打开多个文件,这几个文件可能是经由原来某个文件拆分,分别进行一些处理后希望合并,此时需要同时打开这些文件并读取。通常Python中打开文本使用的是with语句,比如打开一个文件并读取每一行
|
1
2
3
|
为了同时读取多个文件,可以使用下面的代码
|
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的汉语意思是“嵌套的,内装的”,从字面上读者也可能理解了,这个方法跟嵌套有关。前面有一个示例,是从一个文件读取,然后写入到另外一个文件。我不知道读者是否想过可以这么写:
|
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重写。
|
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__()方法。
为了解把这个问题解释清楚,需要先做点别的操作,虽然工程中一般不需要做。
|
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__()。
检验一下,是否按照上述理想路径执行。
|
1
2
3
4
|
1081

被折叠的 条评论
为什么被折叠?



