以下代码逐行读取文件。当从输入文件读入各行时,将每行输出到文本文件(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/