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"的完美对应物是什么?
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
