Python File Handling
Python File Handling is a core Python concept covering python File Handling: --8<-- "core-logic/file-handling.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
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.
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
To delete a file, you must import the os module and use os.remove("filename").
import os
os.remove("demofile.txt")