首页 > 解决方案 > 在 Python 中逐行读取一个大文件,同时写入另一个大文件

问题描述

我试图逐行读取一个大文件,同时写入一个大文件,我想知道这样做的“最佳”方式。

我发现这篇 Stack Overflow 帖子用于逐行读取大文件,并想知道将写入合并到文件的正确方法。有什么比嵌套第二个更好的with open

我目前拥有的:

 #args is parsed from the command line
 #file is an exogenous variable
 with open(args.inPath + file, "r") as fpIn:
   with open(args.outPath + file, "w") as fpOut:
     for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)

标签: pythonfile

解决方案


您不需要嵌套with语句。单个 with 语句可以使用多个上下文管理器。

with open(args.inPath + file, "r") as fpIn, open(args.outPath + file, "w") as fpOut:
    for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)

它有点干净。


推荐阅读