1. Introduction
Once a file is open, Python gives you several methods to read or write its contents depending on whether you want the whole file at once, one line at a time, or all lines as a list. Choosing the right method affects both memory usage and how easy the resulting code is to work with.
Cricket analogy: Choosing read() versus readline() versus readlines() is like choosing to read a full match scorecard at once, ball-by-ball commentary one line at a time, or every over's summary as a list -- each suits a different review need.
For writing, Python offers write() for a single string and writelines() for a sequence of strings, giving you flexibility over how data is produced.
Cricket analogy: write() is like scribbling a single note on the scorecard, while writelines() is like pasting an entire pre-written list of over summaries onto the card in one motion, giving the scorer flexibility in how entries are added.
2. Syntax
# Reading
f.read() # entire file as one string
f.read(n) # up to n characters/bytes
f.readline() # a single line, including the trailing newline
f.readlines() # a list of all lines
# Writing
f.write('text') # write a single string
f.writelines(['a\n', 'b\n']) # write a list of strings (no automatic newlines added)
# Iterating line by line
for line in f:
print(line)3. Explanation
read() loads the entire file into memory as a single string, which is convenient for small files but wasteful for very large ones. readline() reads just the next line (including its trailing '\n'), while readlines() returns every line as a list of strings, each still containing its newline character.
Cricket analogy: read() is like reading the entire match scorecard into your head at once, fine for a single T20 but overwhelming for a five-day Test archive; readline() reads just the next over's line; readlines() lists every over's line including its line break.
writelines() writes each string in the given iterable one after another; unlike print(), it does not add newline characters automatically, so your input strings must already include '\n' where line breaks are needed.
Cricket analogy: writelines() pastes each over-summary string one after another exactly as given, unlike a scoreboard announcer who automatically adds a pause between overs -- so each string must already include its own line-break marker.
Both readline() and readlines() keep the trailing '\n' on each line. A common pattern is to call line.strip() (or .rstrip('\n')) when printing or processing lines to remove that trailing newline.
4. Example
import tempfile, os
path = os.path.join(tempfile.gettempdir(), 'demo_read_write.txt')
f = open(path, 'w')
f.writelines(['apple\n', 'banana\n', 'cherry\n'])
f.close()
f = open(path, 'r')
line1 = f.readline()
rest = f.readlines()
f.close()
print(line1.strip())
for line in rest:
print(line.strip())
os.remove(path)5. Output
apple
banana
cherry6. Key Takeaways
- read() returns the whole file as one string; readlines() returns a list of lines; readline() returns one line at a time.
- writelines() writes an iterable of strings without adding newlines automatically.
- Lines from readline()/readlines() retain their trailing '\n'; use strip() to remove it.
- Iterating directly over a file object ('for line in f') reads it lazily, line by line, which is memory-efficient for large files.
- Reading and writing should be paired with proper closing (or 'with') to avoid resource leaks.
Practice what you learned
1. What does f.readlines() return?
2. Does writelines() automatically insert newline characters between the strings it writes?
3. Which method reads only the next single line from a file?
4. Why might read() be a poor choice for a very large file?
5. What is the memory-efficient way to process a large file line by line?
Was this page helpful?
You May Also Like
File Handling in Python
Understand how to open, read, write, and close files in Python using the built-in open() function and file modes.
with Statement (Context Managers) in Python
Learn how the 'with' statement uses the context manager protocol (__enter__/__exit__) to guarantee cleanup, such as automatically closing files.
Working with JSON in Python
Learn how to convert Python objects to and from JSON using the json module, including dumps/loads for strings and dump/load for files.
os Module in Python
Explore Python's os module for interacting with the operating system, including file paths, directories, and environment information.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics