What is the perfect counterpart in Python for quot;while not EOFquot;(Python 中“虽然不是 EOF的完美对应物是什么?)
问题描述
要在 C 或 Pascal 中读取一些文本文件,我总是使用以下代码段来读取数据,直到 EOF:
To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:
while not eof do begin
readline(a);
do_something;
end;
因此,我想知道如何在 Python 中简单快速地做到这一点?
Thus, I wonder how can I do this simple and fast in Python?
推荐答案
遍历文件读取行:
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
文件对象是可迭代的,并且在 EOF 之前产生行.将文件对象用作可迭代对象使用缓冲区来确保高性能读取.
File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.
你可以对标准输入做同样的事情(不需要使用 raw_input()
:
You can do the same with the stdin (no need to use raw_input()
:
import sys
for line in sys.stdin:
do_something()
为了完成图片,可以通过以下方式完成二进制读取:
To complete the picture, binary reads can be done with:
from functools import partial
with open('somefile', 'rb') as openfileobject:
for chunk in iter(partial(openfileobject.read, 1024), b''):
do_something()
其中 chunk
将包含来自文件的最多 1024 个字节,并且当 openfileobject.read(1024)
开始返回空字节字符串时迭代停止.
where chunk
will contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024)
starts returning empty byte strings.
这篇关于Python 中“虽然不是 EOF"的完美对应物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 中“虽然不是 EOF"的完美对应物是什么?


基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01