您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页python中eof啥意思_什么是Python的完美对应“而不是EOF”

python中eof啥意思_什么是Python的完美对应“而不是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;

Thus, I wonder how can I do this simple and fast in Python?

解决方案

Loop over the file to read lines:

with open('somefile') as openfileobject:

for line in openfileobject:

do_something()

File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.

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

do_something()

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务