python - 在 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)
解决方案
您不需要嵌套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)
它有点干净。
推荐阅读
- ios - 如何将两个 vImage_Buffers 合并为一个 CVPixelBuffer
- android - 如何相对于中心定位图像?
- matlab - 使用扩展方法的模糊算术运算
- c++ - Flutter的invokeMethod上有异步等待C++数据的解决方案吗?
- jquery - 使用 jquery 构建动态数据表给出错误:无法读取未定义的属性“mData”
- r - 在shinyR仪表板中为ggplot2创建动态相关输入过滤器并相应地渲染图
- ruby-on-rails - 在 AWS 中使用 Cloud9 时未找到 ID 为主要的连接池/Gem::LoadError (sqlite3)
- ruby-on-rails - 如何在 Rails 中将模型的实例设置为另一个模型的属性?
- python - 如何使检查网址的过程更快?
- r - tableHTML 中行的条件高亮显示