File Handling in Python
File handling means creating, reading, writing, updating, and deleting files using Python.
Python provides the open() function to work with files.
1. Opening a File
Syntax
file = open("filename", "mode")
Example:
file = open("data.txt", "r")
Here:
"data.txt"→ file name"r"→ read mode
2. File Modes
| Mode | Meaning |
|---|---|
r | Read |
w | Write |
a | Append |
x | Create a new file |
b | Binary mode |
t | Text mode |
+ | Read and write |
Common combinations:
r → read w → write a → append r+ → read + write w+ → write + read a+ → append + read rb → read binary wb → write binary
3. Reading a File
Suppose data.txt contains:
Hello Python Welcome to programming
Using read()
file = open("data.txt", "r") content = file.read() print(content) file.close()
Output:
Hello Python Welcome to programming
4. read(size)
You can specify how many characters to read.
file = open("data.txt", "r") content = file.read(5) print(content) file.close()
Output:
Hello
5. readline()
readline() reads one line at a time.
file = open("data.txt", "r") print(file.readline()) print(file.readline()) file.close()
Output:
Hello Python Welcome to programming
6. readlines()
readlines() reads all lines and returns them as a list.
file = open("data.txt", "r") lines = file.readlines() print(lines) file.close()
Output:
['Hello Python\n', 'Welcome to programming\n']
7. Reading a File Using a Loop
file = open("data.txt", "r") for line in file: print(line) file.close()
This is useful when working with large files.
8. Writing to a File
Use "w" mode to write data.
file = open("data.txt", "w") file.write("Hello Python") file.close()
The file will contain:
Hello Python
Important
"w" mode overwrites existing content.
For example:
file = open("data.txt", "w") file.write("New Content") file.close()
Previous content will be replaced.
9. Writing Multiple Lines
Use \n to create a new line.
file = open("data.txt", "w") file.write("Python\n") file.write("C++\n") file.write("Java\n") file.close()
File content:
Python C++ Java
10. Append to a File
Use "a" mode to add content to the end of a file.
file = open("data.txt", "a") file.write("\nJavaScript") file.close()
If the file previously contained:
Python C++ Java
It becomes:
Python C++ Java JavaScript
Unlike "w", "a" does not remove existing content.
11. Creating a New File
Use "x" mode.
file = open("newfile.txt", "x") file.write("This is a new file") file.close()
If the file already exists, Python will produce an error.
12. Closing a File
After working with a file, it should be closed.
file = open("data.txt", "r") content = file.read() file.close()
Why close a file?
- Releases system resources
- Prevents unnecessary file locking
- Ensures data is properly saved
13. with open() — Recommended Method
Python provides a better way to handle files using with.
with open("data.txt", "r") as file: content = file.read() print(content)
The file is automatically closed after the with block.
You don't need:
file.close()
14. Writing Using with
with open("data.txt", "w") as file: file.write("Learning Python")
The file is automatically closed.
15. Appending Using with
with open("data.txt", "a") as file: file.write("\nLearning File Handling")
16. Checking if a File Exists
Python's os module can be used.
import os if os.path.exists("data.txt"): print("File exists") else: print("File does not exist")
Output:
File exists
17. Deleting a File
Use os.remove().
import os os.remove("data.txt")
Safer Version
import os if os.path.exists("data.txt"): os.remove("data.txt") print("File deleted") else: print("File not found")
18. Creating a Folder
Use os.mkdir().
import os os.mkdir("students")
This creates:
students/
19. Working with File Paths
The os.path module can work with file paths.
import os path = os.path.join("students", "data.txt") print(path)
On Windows, Python handles the appropriate path separator automatically.
20. File Pointer
When reading or writing, Python maintains a file pointer that indicates the current position in the file.
tell()
Returns the current position.
with open("data.txt", "r") as file: print(file.tell()) file.read(5) print(file.tell())
21. seek()
seek() moves the file pointer to a specific position.
with open("data.txt", "r") as file: file.seek(0) print(file.read())
seek(0) moves the pointer back to the beginning.
22. Text Files
Text files store readable characters.
Examples:
.txt .csv .html .py .json
Example:
with open("data.txt", "w") as file: file.write("Hello Python")
23. Binary Files
Binary files store data in binary form.
Examples:
.jpg .png .mp3 .mp4 .pdf .exe
Use "b" mode.
with open("image.jpg", "rb") as file: data = file.read()
24. Copying a Binary File
with open("image.jpg", "rb") as source: data = source.read() with open("copy.jpg", "wb") as destination: destination.write(data)
This reads the image as binary data and writes it to another file.
25. File Encoding
When working with text, you can specify the encoding.
with open("data.txt", "r", encoding="utf-8") as file: content = file.read() print(content)
UTF-8 supports many languages and special characters.
26. Handling File Errors
A file may not exist or may not be accessible.
Use try-except to handle errors.
try: with open("data.txt", "r") as file: print(file.read()) except FileNotFoundError: print("File not found")
Output if the file doesn't exist:
File not found
27. Complete Example
filename = "student.txt" # Write with open(filename, "w") as file: file.write("Name: Ram\n") file.write("Age: 20\n") file.write("Course: Computer Engineering\n") # Read with open(filename, "r") as file: content = file.read() print(content)
Output:
Name: Ram Age: 20 Course: Computer Engineering
File Handling Summary
| Operation | Method |
|---|---|
| Open file | open() |
| Read all | read() |
| Read one line | readline() |
| Read all lines | readlines() |
| Write | write() |
| Write multiple strings | writelines() |
| Current position | tell() |
| Move position | seek() |
| Close | close() |
| Check file | os.path.exists() |
| Delete file | os.remove() |
| Create folder | os.mkdir() |
Basic File Handling Flow
Open File ↓ Read / Write / Append ↓ Process Data ↓ Close File
Most Recommended Pattern
with open("data.txt", "r") as file: data = file.read()
Using with open() is preferred because Python automatically closes the file after the block finishes.