python一次读1000个,直到文件结束? [英] python read 1000 at a time until end of file?
问题描述
with open(localFileTT,'rb',0)as f:#open the (fstr)
print(fstr)
fstr中的'str':
break
我还没有在这个代码中引入网络功能,因为它只是测试材料,弄清楚如何只读1000时间。它当然能够读取整个部分,但我不知道如何改变它,以便一次只读取部分内容。我会尝试加入阅读(1000),但打印空虚!我不确定阅读是在哪里发生的,不幸的是,迄今为止在线阅读的这些代码的部分文章(例如,)没有任何帮助。如果有人能指出我的方向,那么我会很感激。
解决方案 file.read()
需要大小 em>参数:
$ b
从文件中读取至多 size 字节
size
字节)。如果size
参数为负值或省略,则读取所有数据,直到到达EOF。
您可以在循环中使用它,并结合 iter()
函数(将第二个参数设置为作为标记)和
functools.partial()
的效率:
从functools导入部分
打开(localFileTT,'rb',0)作为f:
(部分(f.read,1000),''):
#chunk长达1000个字符
另一种方法是在循环中使用:
打开(localFileTT,'rb',0)作为f:
而真:
chunk = f.read(1000)
如果不是大块:
#已到达EOF ,结束循环
bre ak
#chunk长达1000个字符
如果您已经试过读取(1000)
并得到一个空字符串,当时您的文件已经在EOF。
I've been working on a python project to send information to a server, and while I found some nice code to read the file and send it, I can only send the entire thing at once. I want instead to be able to read 1000 characters at a time, and loop until the file's end. I'm sure that this is pretty easy, but I'm not sure where to change what I've been doing to make it happen. This might also be due to unfamiliarity with the method of reading, but I am researching it and not finding any information that has clarified it for me. This is what I'm working with:
with open(localFileTT, 'rb', 0) as f: #open the file
for fstr in f:
str.encode(fstr)
print(fstr)
if 'str' in fstr:
break
I have not yet introduced network functions in this code, as it is only test material to figure out how to read only 1000 at a time. It certainly reads the entire section well enough, but I don't know how to change it so as to read only parts at a time. I would try just adding read(1000) but that prints emptiness! I'm not sure where exactly the reading is occurring here, and unfortunately the articles I've read online thus far on parts of this code (such as with) has not helped any. If anyone can point me in the right direction, then I will be quite grateful.
file.read()
takes a size argument:
Read at most size bytes from the file (less if the read hits EOF before obtaining
size
bytes). If thesize
argument is negative or omitted, read all data until EOF is reached.
You can use that in a loop, combined with the iter()
function (with the second argument set to ''
as a sentinel), and functools.partial()
for efficiency:
from functools import partial
with open(localFileTT, 'rb', 0) as f:
for chunk in iter(partial(f.read, 1000), ''):
# chunk is up to 1000 characters long
The alternative would be to use a while
loop:
with open(localFileTT, 'rb', 0) as f:
while True:
chunk = f.read(1000)
if not chunk:
# EOF reached, end loop
break
# chunk is up to 1000 characters long
If you already tried read(1000)
and got an empty string back, your file was already at EOF at the time.
这篇关于python一次读1000个,直到文件结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!