我需要打开多个文件(2个输入和2个输出文件),对输入文件的行进行复杂的操作,然后在2个输出文件的末尾附加结果.我目前正在使用以下方法:
in_1 = open(input_1)
in_2 = open(input_2)
out_1 = open(output_1, "w")
out_2 = open(output_2, "w")
# Read one line from each 'in_' file
# Do many operations on the DNA sequences included in the input files
# Append one line to each 'out_' file
in_1.close()
in_2.close()
out_1.close()
out_2.close()
Run Code Online (Sandbox Code Playgroud)
文件很大(每个都可能接近1Go,这就是为什么我一次只读取这些输入文件.我猜这不是一种非常恐怖的做事方式.:)使用下面的表格好吗?
with open("file1") as f1:
with open("file2") as f2:
with open("file3") as f3:
with open("file4") as f4:
# Read one line from each 'in_' file
# Do many operations on the DNA sequences...
# Append one line to each 'out_' file
Run Code Online (Sandbox Code Playgroud)
如果是的话,我可以这样做,同时避免高度缩进的代码(注释部分,它本身可能包含缩进行.除非,如我所知,我事先使用适当定义的函数)?感谢您的见解!
contextlib.nested() 允许您在单个语句中链接多个上下文管理器:
with contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):
....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1545 次 |
| 最近记录: |