Index
What is File Handling?
File handling means your Python program can:
- Create
- Read
- Write
- Append
- Delete
files like .txt
, .csv
, etc.
Why Use File Handling?
To save and access data permanently (outside the program), like:
- Saving user input
- Reading from configuration files
- Logging information
- Managing reports, etc.
Basic File Operations in Python
Mode | Meaning | Description |
---|---|---|
'r' | Read | Opens file for reading (default) |
'w' | Write | Overwrites file or creates new |
'a' | Append | Adds to the end of file |
'x' | Create | Creates file, error if exists |
'rb' | Read Binary | For files like images, etc. |
Basic Example: Read and Write
Writing to a file
file = open("demo.txt", "w")
file.write("Hello, this is Python file handling!")
file.close()
This creates a file demo.txt
and writes a line inside it.
Reading from a file
file = open("demo.txt", "r")
content = file.read()
print(content)
file.close()
Appending to a file
file = open("demo.txt", "a")
file.write("\nNew line added!")
file.close()
Delete a File
Use the os module to delete a file:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("File not found.")
Using with
(Best Practice)
with open("demo.txt", "r") as file:
content = file.read()
print(content)
The with
block automatically closes the file after use.
Summary
Operation | Function |
---|---|
Create | open("file.txt", "x") |
Read | open("file.txt", "r") |
Write | open("file.txt", "w") |
Append | open("file.txt", "a") |
Best way | Use with open(...) as ...: |