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¶
- Text Files (
.txt): Plain text, easy to read for humans. - CSV Files (
.csv): "Comma Separated Values". Think of it as a simple spreadsheet. - JSON Files (
.json): "JavaScript Object Notation". The most popular format for web data. - Binary Files: Images, audio, or custom formats that only computers can read.
The File Lifecycle¶
- Open: Tell the OS you want to use the file.
- Mode: Decide if you want to Read (
r), Write (w), or Append (a). - Process: Read or write the actual data.
- 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!