How can I read a text file one line at a time in Python?
Quick answer
Open the file and loop over it with for line in file: to handle its lines one at a time. A line read from a text file normally still includes its newline. If you need to remove that ending while preserving spaces, use line.rstrip("\n"). By contrast, read() returns the entire file contents as one string. [S1]
The question, the details, the next step.
A practical checklist
Replace
sample.txtwith the path to your file.Open the file and loop with
for line in file:.Use
line.rstrip("\n")when you need text without its newline.Avoid
strip()if leading or trailing spaces must be preserved.Use
print(line, end="")when the line already includes a newline and you want to avoid adding another.
A few more useful answers
Does each line still include its newline?
Normally, yes: a line read from a text file retains its newline. In text mode, platform-specific line endings are translated to \n. [S1]
What is the difference between `readline()` and `read()`?
readline() reads one line and normally leaves its newline at the end. read() returns the entire file contents as one string. [S1]
Does reading line by line guarantee lower memory use?
The documented distinction is that read() returns the whole file as one string, whereas readline() reads one line. That alone does not establish memory use or performance for a particular program. [S1]
Sources
References used for this guide.
- [S1] Python Tutorial: Reading and writing files docs.python.org · Checked
