Text File Handling in Python
Open, write, read and append text files in Python, close them safely with with, and move around a file using seek() and tell().
Learning objectives
- βChoose the right file mode: r, w, a, r+, w+ or a+
- βWrite with write() and writelines(); read with read(), readline() and readlines()
- βUse with so that files are always closed
- βProcess a file line by line and use seek() and tell() to move the file pointer
π‘ Key points
- open(name, mode) returns a file object. Close it with close(), or better, use a with block that closes it for you.
- 'r' reads (the file must exist), 'w' writes (creates the file or ERASES the old content), 'a' appends to the end.
- Adding + allows both reading and writing: r+ does not erase the file, w+ erases it first, a+ writes only at the end.
- read() returns the whole file as one string, readline() returns the next line, readlines() returns a list of all lines.
- write() takes one string and writelines() takes a list of strings; neither adds newlines for you.
- Each line you read (except perhaps the last) still has its newline character at the end; strip() it before comparing or printing.
- tell() gives the current position in the file; seek(n) moves to position n, and seek(0) goes back to the start.
π» Code examples(6)
f = open("poem.txt", "w")
f.write("Twinkle twinkle little star\n")
f.write("How I wonder what you are\n")
f.write("Up above the world so high\n")
f.close()
print("Saved poem.txt")
Saved poem.txt
with open("poem.txt", "r") as f:
print(f.readline(), end="") # one line
print(f.readline().strip()) # remove the \n
rest = f.readlines() # remaining lines
print(rest)
with open("poem.txt") as f: # "r" is default
text = f.read() # whole file
print(len(text), "characters")
Twinkle twinkle little star How I wonder what you are ['Up above the world so high\n'] 81 characters
more = ["Like a diamond in the sky\n",
"Twinkle twinkle little star\n"]
with open("poem.txt", "a") as f:
f.writelines(more)
with open("poem.txt") as f:
for n, line in enumerate(f, start=1):
print(n, line.rstrip())
1 Twinkle twinkle little star 2 How I wonder what you are 3 Up above the world so high 4 Like a diamond in the sky 5 Twinkle twinkle little star
lines = words = t_lines = 0
with open("poem.txt") as f:
for line in f:
lines += 1
words += len(line.split())
if line.startswith("T"):
t_lines += 1
print("Lines:", lines)
print("Words:", words)
print("Lines starting with T:", t_lines)
Lines: 5 Words: 26 Lines starting with T: 2
with open("poem.txt") as f:
print(f.tell()) # 0: at the start
print(f.read(7)) # read 7 characters
print(f.tell()) # now at 7
f.seek(8) # jump to position 8
print(f.read(7))
f.seek(0) # back to the start
print(f.readline().strip())
0 Twinkle 7 twinkle Twinkle twinkle little star
with open("poem.txt") as src:
lines = src.readlines()
with open("other.txt", "w") as dst:
for line in lines:
if not line.startswith("T"):
dst.write(line)
with open("other.txt") as f:
print(f.read(), end="")
How I wonder what you are Up above the world so high Like a diamond in the sky
π― Practice
Q1. Which mode adds new lines to the end of an existing file without erasing it?+
'a' (append), or 'a+' if you also want to read.
Q2. What is the difference between read(), readline() and readlines()?+
read() returns the whole file as one string. readline() returns just the next line. readlines() returns a list containing every line.
Q3. Write a program that counts the lines in story.txt that start with 'A'.+
count = 0 with open('story.txt') as f: for line in f: if line.startswith('A'): count += 1 print(count)
Q4. What happens if you open a file that does not exist in 'r' mode? In 'w' mode?+
'r' raises FileNotFoundError. 'w' creates a new empty file.
Q5. What does f.seek(0) do?+
It moves the file pointer back to the beginning, so the next read starts from the first character again.
π Notes
File modes in one place
"r"read only. File must exist. Pointer at the start. This is the default."w"write only. Creates the file, or erases it if it exists."a"append only. Creates the file if needed; every write goes to the end."r+"read and write. File must exist; nothing is erased, but the pointer starts at the beginning, so a write overwrites the text there."w+"read and write. Creates the file, or erases it first."a+"read and append. Creates the file if needed; the pointer starts at the end, soseek(0)before reading. Writes always go to the end.
Why with is better than close()
If an error happens between open() and close(), the close() line never runs, and data you wrote may not be saved. A with block always closes the file when the block ends:
with open("log.txt", "a") as f:
f.write("Logged in\n")
# file is closed here
Paths
A plain name like "poem.txt" means the folder your program runs from. You can also give a full path. On Windows, use a raw string so backslashes are not treated as escape sequences:
f = open(r"C:\school\marks.txt")
Handling a missing file
Combine today's topic with Day 16:
try:
with open("marks.txt") as f:
print(f.read())
except FileNotFoundError:
print("marks.txt not found")
Common mistakes
- Opening with "w" by accident: the old contents are gone immediately.
- Forgetting \n in
write(): all lines run together. - Comparing lines without strip():
line == "Amit"isFalsewhen the line is really"Amit\n". - Writing numbers:
f.write(95)raises TypeError. Writestr(95)or use an f-string. - Reading twice: after
read(), the pointer is at the end, so a secondread()returns"". Useseek(0)first.
Next: Day 18 β Binary and CSV Files, for storing whole Python objects and spreadsheet-style data.