Skip to content

Python File Handling

File Handling: Storing Data Permanently

Usually, when a program stops, all its data is lost. File Handling allows a program to read from and write to files on your hard drive, making data persistent.

Common File Formats

  1. Text Files (.txt): Plain text, easy to read for humans.
  2. CSV Files (.csv): "Comma Separated Values". Think of it as a simple spreadsheet.
  3. JSON Files (.json): "JavaScript Object Notation". The most popular format for web data.
  4. Binary Files: Images, audio, or custom formats that only computers can read.

The File Lifecycle

  1. Open: Tell the OS you want to use the file.
  2. Mode: Decide if you want to Read (r), Write (w), or Append (a).
  3. Process: Read or write the actual data.
  4. Close: Very important! Tells the OS you are done so other programs can use the file.

Context Managers

Modern languages have a "Context Manager" (like Python's with statement) that automatically closes the file for you, even if an error occurs!

Opening a File

Python has a built-in open() function. It takes two parameters: filename and mode.

Mode Description
"r" Read: Opens a file for reading. Error if file doesn't exist.
"a" Append: Opens for appending. Creates file if doesn't exist.
"w" Write: Opens for writing. Overwrites existing content.
"x" Create: Creates a new file. Error if file exists.

Reading a File

f = open("demofile.txt", "r")
print(f.read())
f.close() # Always close!

Writing to a File

f = open("demofile.txt", "w")
f.write("Now the file has more content!")
f.close()

The Best Way: with Statement

Using the with statement is the best practice because it automatically closes the file for you.

with open("demofile.txt", "r") as f:
    content = f.read()
    print(content)
# File is automatically closed here

Deleting Files

To delete a file, you must import the os module and use os.remove("filename").

import os
os.remove("demofile.txt")