Text Files: open, read, write, seek
Why files?
Variables live in RAM and disappear when the program ends. To keep data — marks, bills, game scores — for later, we store it in a file on secondary storage. Python can create, read, write and update files.
Text, binary and CSV files
File names and paths
An absolute path gives the full location: C:\Users\Riya\Documents\poem.txt. A relative path is relative to the folder where the program runs: poem.txt or data/poem.txt. In Windows paths use a raw string r'C:\data\poem.txt' or forward slashes 'C:/data/poem.txt' so that \p is not treated as an escape.
Opening and closing a file
file_object = open(file_name, mode) ... file_object.close()
open() returns a file object (also called a file handle). Default mode is 'r'.
File modes
| Mode | Meaning | If file does not exist | Pointer starts at |
|---|---|---|---|
| r | Read only (default) | FileNotFoundError | Beginning |
| w | Write only – erases old content | Creates it | Beginning |
| a | Append only | Creates it | End |
| r+ | Read and write | FileNotFoundError | Beginning |
| w+ | Write and read – erases old content | Creates it | Beginning |
| a+ | Append and read | Creates it | End |
| x | Create new file only | Creates it (error if it exists) | Beginning |
Add b for binary files: rb, wb, ab, rb+ …
Writing: write() and writelines()
write(string) writes one string and returns the number of characters written. writelines(list) writes every string of a list. Neither adds \n automatically.
f = open('poem.txt', 'w') # create / overwrite
f.write('Twinkle twinkle little star\n')
f.write('How I wonder what you are\n')
f.writelines(['Up above the world so high\n', 'Like a diamond in the sky\n'])
f.close()
print('poem.txt written')Reading: read(), readline(), readlines()
f = open('poem.txt', 'r')
print(f.read(7)) # first 7 characters
print(f.readline(), end='') # rest of the current line
print(f.readlines()) # all remaining lines as a list
f.close()| Method | Returns | Type |
|---|---|---|
| read() | whole remaining file | str |
| read(n) | next n characters | str |
| readline() | next line (with \n) | str |
| readlines() | all remaining lines | list of str |
The file pointer moves forward as you read; each method continues from where the last one stopped.
The with statement
with open('poem.txt') as f: # file closes automatically
text = f.read()
print(repr(text))
print('Characters:', len(text))On Windows each \n is stored as two bytes (\r\n), so the file size on disk may be larger than len(text).
Reading line by line
Looping over the file object is the most memory-efficient way — perfect for big files.
with open('poem.txt') as f:
for line in f: # the file object is iterable, line by line
print(line.strip().upper())Appending data
with open('poem.txt', 'a') as f: # append keeps old data
f.write('Twinkle twinkle little star\n')
with open('poem.txt') as f:
lines = f.readlines()
print('Lines now:', len(lines))
print('Last line:', lines[-1].strip())seek() and tell()
tell() returns the current position of the file pointer (in bytes from the start). seek(offset) moves it. In binary mode seek(offset, whence) can move from the start (0), current position (1) or end (2).
with open('poem.txt') as f:
print(f.tell()) # position at start
print(f.read(5))
print(f.tell()) # moved 5 characters
f.seek(8) # jump to position 8
print(f.read(7))
f.seek(0) # back to the beginning
print(f.readline().strip())Saving user input
n = int(input('How many students? '))
with open('students.txt', 'w') as f:
for i in range(n):
name = input('Name: ')
marks = input('Marks: ')
f.write(name + ',' + marks + '\n')
with open('students.txt') as f:
print(f.read(), end='')try:
with open('notes.txt') as f:
print(f.read())
except FileNotFoundError:
print('notes.txt does not exist yet')Summary & practice
open(name, mode)→ file object; always close or usewith.- Modes: r, w, a, r+, w+, a+, x (+ b for binary).
- write / writelines; read / readline / readlines; iterate with for.
- tell() gives the position; seek() moves it.
1) Write a program to copy all lines of poem.txt that contain the word "the" into another file. 2) Which mode would you use to add a new student to students.txt without deleting others? 3) What does f.read(0) return?
Answers: 2) 'a'. 3) An empty string ''.
