Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📁 Unit 1 – File Handling  ·  Lesson 05

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.

Program (RAM)data in variableswrite()saveFile on diskpoem.txt – permanentread()load later
Files make data permanent

Text, binary and CSV files

📄
Text fileHuman-readable characters; each line ends with a newline (\n). .txt, .py, .html
🧱
Binary fileRaw bytes, not human-readable: images, audio, Python objects saved with pickle (.dat).
📊
CSV fileText file with comma-separated values in rows, opens in Excel.
Three file types in the syllabus

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

Syntax
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

ModeMeaningIf file does not existPointer starts at
rRead only (default)FileNotFoundErrorBeginning
wWrite only – erases old contentCreates itBeginning
aAppend onlyCreates itEnd
r+Read and writeFileNotFoundErrorBeginning
w+Write and read – erases old contentCreates itBeginning
a+Append and readCreates itEnd
xCreate new file onlyCreates 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.

Python
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')
poem.txt written

Reading: read(), readline(), readlines()

Python
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()
Twinkle twinkle little star ['How I wonder what you are\n', 'Up above the world so high\n', 'Like a diamond in the sky\n']
MethodReturnsType
read()whole remaining filestr
read(n)next n charactersstr
readline()next line (with \n)str
readlines()all remaining lineslist of str
Reading methods compared

The file pointer moves forward as you read; each method continues from where the last one stopped.

The with statement

Python
with open('poem.txt') as f:        # file closes automatically
    text = f.read()
print(repr(text))
print('Characters:', len(text))
'Twinkle twinkle little star\nHow I wonder what you are\nUp above the world so high\nLike a diamond in the sky\n' Characters: 107

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.

Python
with open('poem.txt') as f:
    for line in f:                 # the file object is iterable, line by line
        print(line.strip().upper())
TWINKLE TWINKLE LITTLE STAR HOW I WONDER WHAT YOU ARE UP ABOVE THE WORLD SO HIGH LIKE A DIAMOND IN THE SKY

Appending data

Python
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())
Lines now: 5 Last line: Twinkle twinkle little star

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).

Python
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())
0 Twink 5 twinkle Twinkle twinkle little star
T0w1i2n3k4l5e6␣7t8seek(8)w9i10n11k12l13e14
After seek(8), read(7) returns "twinkle"

Saving user input

Python
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='')
How many students? 3 Name: Asha Marks: 88 Name: Ravi Marks: 72 Name: Neha Marks: 95 Asha,88 Ravi,72 Neha,95
Python
try:
    with open('notes.txt') as f:
        print(f.read())
except FileNotFoundError:
    print('notes.txt does not exist yet')
notes.txt does not exist yet

Summary & practice

  • open(name, mode) → file object; always close or use with.
  • 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.
✅ Practice

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 ''.

Frequently Asked Questions

What is the difference between w and a modes?
"w" creates a new file or erases an existing one before writing. "a" opens the file and adds new data at the end, keeping the old content; it also creates the file if it does not exist.
What is the difference between read(), readline() and readlines()?
read() returns the whole remaining file (or n characters) as one string; readline() returns one line; readlines() returns all remaining lines as a list of strings.
Why should a file be closed?
Closing writes any buffered data to the disk and frees the file for other programs. The with statement closes the file automatically, even if an error occurs.
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicText File Programs (Board Pattern) Your progress: 5 / 26 (19%) · Lesson 6 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free