什么是Python的完美对应“而不是EOF”

编程入门 行业动态 更新时间:2024-10-07 16:25:04
本文介绍了什么是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.

您可以对stdin执行相同操作(不需要使用 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()

要完成图片,可以使用二进制读取: / p>

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), ''): do_something()

其中 chunk 将一次最多包含1024个字节。

where chunk will contain up to 1024 bytes at a time from the file.

更多推荐

什么是Python的完美对应“而不是EOF”

本文发布于:2023-11-29 15:42:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646831.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   完美   Python   EOF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!