Use a for loop on a file object to read it line-by-line. Use with open(...) to let a context manager ensure that the file is closed after reading:
with open("log.txt") as infile:
for line in infile:
print(line)
Answer from John La Rooy on Stack OverflowUse a for loop on a file object to read it line-by-line. Use with open(...) to let a context manager ensure that the file is closed after reading:
with open("log.txt") as infile:
for line in infile:
print(line)
All you need to do is use the file object as an iterator.
for line in open("log.txt"):
do_something_with(line)
Even better is using context manager in recent Python versions.
with open("log.txt") as fileobject:
for line in fileobject:
do_something_with(line)
This will automatically close the file as well.
How do I read in a large file in chunks?
Any trick to load few big files in Python?
Non-horrible way to parse large text files?
I often have to parse large text files
How large is a "large file" ? The last person that had this problem here had a few thousand lines.
Post an example file and one of your programs that parses it and someone can tell you what you are doing wrong. Otherwise, who the hell knows.
for line in file runs at about 1,500,000 lines/second on my laptop. so no, python is not slow.
Best way to process manipulate large files without reading entire file into memory
Hello,
I would like to know how to best approach the following task.
I have a large file which is a few million lines. I want to read each line and do something with it.
Considerations:
-
I don’t want the whole file loaded into memory at once, I want this loaded in chunks
-
Threading should be used (unless there’s a better option)
My initial thought process in pseudocode would be something like:
lines_at_once = 100000
for line in read(file, lines_at_once):
do_something(line)