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?
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?
You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.
The Python idiom for opening a file and reading it line-by-line is:
The file will be automatically closed at the end of the above code (the
with
construct takes care of that).Finally, it is worth noting that
line
will preserve the trailing newline. This can be easily removed using:Loop over the file to read lines:
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()
:To complete the picture, binary reads can be done with:
where
chunk
will contain up to 1024 bytes at a time from the file, and iteration stops whenopenfileobject.read(1024)
starts returning empty byte strings.You can use below code snippet to read line by line, till end of file
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
Example:
Or press Ctrl-Z at a
raw_input()
prompt (Windows, Ctrl-Z Linux)You can imitate the C idiom in Python.
To read a buffer up to
max_size
number of bytes, you can do this:Or, a text file line by line:
You need to use
while True / break
construct since there is no eof test in Python other than the lack of bytes returned from a read.In C, you might have:
However, you cannot have this in Python:
because assignments are not allowed in expressions in Python.
It is certainly more idiomatic in Python to do this: