Skip to content

Class 12 · Computer Science · Computer Science

Chapter 2: File Handling in Python Notes

The big idea

Files store data permanently on disk. Python opens them with open(), reads and writes text files with simple methods, jumps around with seek and tell, and saves whole objects in binary files using pickle.

Things to remember

  • A file is a named location on secondary storage that keeps data permanently. Text files hold readable characters (.txt, .py, .csv) with lines ending in the EOL character; binary files hold raw bytes such as images and need special programs.
  • file_object = open(file_name, access_mode) returns a file handle. Modes: r read (default), w write (erases old data), a append (adds at end), plus + for read and write, and b for binary. File attributes include closed, mode and name.
  • close() frees resources and flushes unwritten data. The with clause, as in with open(name, mode) as f, closes the file automatically when its block ends, even if an exception occurs, so it is the safest way to work with files.
  • write(string) writes one string and returns the number of characters written; add the newline character yourself. writelines(list) writes a sequence of strings and returns nothing. Numbers must be converted with str() first. Data sits in a buffer until close() or flush().
  • read(n) reads n characters, or the whole file if n is omitted or negative. readline() reads one line including the newline and returns an empty string at end of file. readlines() returns all lines as a list of strings. split() breaks a line into words.
  • tell() returns the current byte position of the file object. seek(offset, reference) moves it: reference 0 is the beginning (default), 1 is the current position, 2 is the end. This allows random access instead of only sequential reading.
  • The pickle module serialises (pickles) a Python object into a byte stream and de-serialises (unpickles) it back. Use import pickle, open the file in wb mode and call pickle.dump(object, file); read with rb mode and pickle.load(file).
  • A loop of pickle.load calls on a binary file ends with EOFError at end of file, so it is placed inside try and except EOFError. Exam tip: w erases an existing file, a keeps it, and pickle files must use binary modes.

Words to know

Tap a card to see what it means

Quick quiz

⭐ 0 / 5
  1. A file opened in mode w already contains notes. What happens to the old notes when new data is written?

  2. What does myobject.write('Hello\n') return, where the string has the five letters of Hello plus one newline?

  3. The file holds three lines: Hello everyone, Writing multiline strings, This is the third line. After f.read(10) is executed on a fresh file object, what does f.tell() return?

  4. Which statements correctly save the list data to a binary file using pickle?

  5. Assertion (A): A file opened with the with clause need not be closed explicitly. Reason (R): The with clause closes the file automatically when control leaves its block, even after an exception. Choose the correct option.

Match the pairs

Match each file method or mode with its job.

Try this at home

With an adult, write a short Python program that saves three of your favourite foods to a text file using write, then reads the file back line by line and prints it. Then try opening it in append mode and add one more food.

All Computer Science notesChapter page and exercisesComputer Science syllabus