简体   繁体   English

Python:逐行解析和打印文本文件

[英]Python: Parse and Print Text File Line by Line

I have the following question. 我有以下问题。 How can I print an output file line by line. 如何逐行打印输出文件。 A simple example that i can think is the following. 我能想到的一个简单例子如下。 Any idea? 任何想法?

import codecs
output=codecs.open('output.txt','w', encoding='UTF-8')
for i in range(5):
   output.writelines(str(i)+'\n')
output.close()

I import codecs because maybe the input can be something else and not just the value i . 我导入codecs因为输入可能是其他东西而不仅仅是值i

I take the following result: 我采取以下结果:

01234

instead of: 代替:

0
1
2
3
4

Your code does output newlines. 您的代码确实输出了换行符。 Check that your editor recognizes \\n newlines. 检查您的编辑器是否识别\\n换行符。 However, it does so by accident. 但是,它是偶然的。 writelines expects a sequence of lines: writelines期望一系列的行:

with open('output.txt','w', encoding='UTF-8') as output:
  output.writelines(str(i)+'\n' for i in range(5))

Try using write instead of writelines . 尝试使用write而不是writelines

writelines(sequence_of_strings) -> None. writelines(sequence_of_strings) - >无。 Write the strings to the file. 将字符串写入文件。

Note that newlines are not added. 请注意,不会添加换行符。 The sequence can be any iterable object producing strings. 序列可以是生成字符串的任何可迭代对象。 This is equivalent to calling write() for each string. 这相当于为每个字符串调用write()。

On the other hand: 另一方面:

write(str) -> None. 写(str) - >无。 Write string str to file. 将字符串str写入文件。

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. 请注意,由于缓冲,在磁盘上的文件反映写入的数据之前可能需要flush()或close()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM