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¶
- 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!
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¶
Writing to a File¶
The Best Way: with Statement¶
Using the with statement is the best practice because it automatically closes the file for you.