Skip to content

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!