File Handling in Python
File handling is a crucial part of Python programming. It allows you to store, retrieve, and manipulate data stored in files such as text or binary files.
1. Opening and Closing a File
This example shows how to open and close a text file.
file = open("example.txt", "r") print(file.read()) file.close()
Explanation: This code opens a file named example.txt in read mode (r), prints its content, and then closes the file.
2. Writing to a File
file = open("output.txt", "w") file.write("Hello, world!") file.close()
Explanation: This code creates or overwrites output.txt and writes "Hello, world!" to it.
3. Appending to a File
file = open("output.txt", "a") file.write("\nAppended line.") file.close()
Explanation: This opens the file in append mode and adds a new line without overwriting existing content.
4. Reading Line by Line
file = open("example.txt", "r") for line in file: print(line.strip()) file.close()
Explanation: This reads each line from the file and prints it without extra newline characters.
5. Using with Statement (Context Manager)
with open("example.txt", "r") as file: data = file.read() print(data)
Explanation: The with statement automatically handles file closing, even if an error occurs.
6. File Modes Explained
r– Read (default mode)w– Write (overwrite)a– Appendr+– Read and writewb– Write binaryrb– Read binary
7. Reading a File into a List
with open("example.txt") as file: lines = file.readlines() print(lines)
Explanation: The readlines() method reads all lines and returns them as a list.
8. Checking if File Exists
import os if os.path.exists("example.txt"): print("File exists!") else: print("File does not exist.")
Explanation: This checks whether a file exists using the os module.
9. Reading a Binary File
with open("image.png", "rb") as file: content = file.read() print("Bytes read:", len(content))
Explanation: This opens an image in binary read mode and prints the byte size.
10. Writing to a File Using a List
lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("lines.txt", "w") as file: file.writelines(lines)
Explanation: This code writes multiple lines to a file using writelines().