Does Python read 1000 at a time to the end of the file?

I was working on a python project to send information to the server, and while I found good code to read the file and send it, I can send everything at once. Instead, I want to be able to read 1000 characters at a time and loop to the end of the file. I'm sure this is pretty easy, but I'm not sure where to change what I did to make this happen. It may also be due to ignorance with the reading method, but I study it and I can not find any information that clarified this for me. This is what I work 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 the network functions in this code, as this is only test material to figure out how to read only 1000 at a time. Of course, he reads the entire section well enough, but I don’t know how to change it to read only parts at a time. I would try just adding a read (1000), but that prints a void! I’m not sure exactly where the reading is taking place, and, unfortunately, the articles that I read on the Internet have so far not helped on parts of this code (for example, c). If someone can point me in the right direction, then I will be very grateful.

+3
source share
1 answer

file.read() takes a size argument:

Read files no larger than bytes in size (smaller if reading falls into EOF before receiving size bytes). If the size argument is negative or omitted, read all the data until EOF is reached.

You can use this in a loop in combination with the iter() function (with the second argument set to '' as a functools.partial() '' ), 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 

An alternative would be to use a while :

 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 have already tried read(1000) and received an empty line, your file was already on EOF at the moment.

+7
source

Source: https://habr.com/ru/post/1014556/


All Articles