python - 当数据流入 python 时,将数据输出到文本文件中

标签 python fileoutputstream

以下代码逐行读取文件。当从输入文件读入各行时,将每行输出到文本文件(output.txt)的最有效方法是什么?

fileHandle = open('file', 'r')

for line in fileHandle:
    fields = line.split('|')

    print(fields[0]) # prints the first fields value
    print(fields[1]) # prints the second fields value

fileHandle.close()

上面的代码可以在 Parsing a pipe delimited file in python 中找到

最佳答案

一种有效的方法是使用生成器上下文管理器来处理文件。上下文管理器负责关闭文件。生成器将一次生成一行,而不是首先构建临时列表。

with open('read_file', 'r') as reader:
    with open('output_file', 'w') as writer:
        gen = (line.split('|') for line in reader)
        for row in gen:
            writer.write(row)

关于python - 当数据流入 python 时,将数据输出到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997739/

相关文章:

Python Redis 队列 (rq) - 如何避免为每个作业预加载 ML 模型?

android - FileNotFoundException :/storage/sdcard0/Myfile. txt:打开失败:EACCES(权限被拒绝)

android - 如何让用户访问我的应用程序的内部存储目录?

java - 为什么java FileOutputStream的write()或flush()不能使NFS客户端真正向NFS服务器发送数据?

android - FileOutputStream wit 数据库文件在 Android 9 上不再工作

python - 如何获取文件夹中文件的序号?

python - 从包的 __init__.py 中屏蔽 python 子模块

Python:绘制筛选点返回图片上的点

python - Django:使用户电子邮件成为必需的

Java - 使用 FileOutputStream append 到 Excel 文件