Skip to content

Language

Sign in

Learn › Class 12 › Computer Science / Informatics Practices › File handling and data structures (stack)

File handling

You will learn to

  • Open, read, write and close text files using the right mode
  • Store and load Python objects in binary files with pickle
  • Read and write CSV files with the csv module

Helpful to know first: Strings and lists; Exception handling.

A text file stores characters in lines that end with a newline. A binary file stores raw bytes, such as images or pickled objects. A CSV file is a text file with comma-separated values.

File modes

'r' reads (error if missing). 'w' writes and erases old content, creating the file if needed. 'a' adds to the end. '+' adds the other operation, as in 'r+'. A 'b' suffix, as in 'rb', means binary.

with open('marks.txt', 'r') as f: closes the file automatically when the block ends. Without with, you must call f.close() yourself.

read() returns the whole file as one string, and read(n) returns n characters. readline() returns one line, and readlines() returns a list of lines. write() and writelines() do not add newlines for you.

tell() gives the current position in the file and seek(n) moves to position n. pickle.dump(obj, f) saves an object to a file opened with 'wb'. pickle.load(f) reads one back and raises EOFError at the end.

For CSV, csv.writer(f).writerow(list) writes one row and csv.reader(f) gives each row as a list. Open CSV files with newline='' to avoid blank lines on Windows.

Common mix-ups

  • Not quite: Opening a file in 'w' mode adds to what is already there.

    Instead: 'w' erases the file first. Use 'a' to add to the end.

  • Not quite: writelines() puts each string on its own line.

    Instead: It writes the strings one after another. You must include '\n' at the end of each string yourself.

Reviewed by EduFlint team on 1 Dec 2026 · version 1

Written by us for this site. Independent; not affiliated with NCERT or CBSE.

Report a mistake

Looking for another topic?