File Handling in Python
File handling in Python allows you to read from and write to files. Python provides built-in functions to work with files, making it easy to handle text and binary files. File handling is essential for tasks like data storage, configuration management, and logging.
Opening a File
Use the open() function to open a file. You can specify the mode (e.g., read, write, append).
# Open a file in read mode
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Writing to a File
Use the write() method to write data to a file. If the file does not exist, it will be created.
# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
Appending to a File
Use the append mode to add content to the end of a file without overwriting it.
# Open a file in append mode
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()
Using with Statement
The with statement automatically closes the file after the block is executed, even if an exception occurs.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Lines from a File
You can read a file line by line using the readline() or readlines() methods.
# Read line by line
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line, end="")
line = file.readline()
# Read all lines at once
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end="")
Working with Binary Files
Binary files (e.g., images, videos) can be read and written using the rb (read binary) and wb (write binary) modes.
# Reading a binary file
with open("image.png", "rb") as file:
binary_data = file.read()
# Writing to a binary file
with open("copy.png", "wb") as file:
file.write(binary_data)
File Modes
Python supports various file modes for different operations:
r: Read mode (default).w: Write mode (overwrites the file).a: Append mode (adds to the end of the file).rb: Read binary mode.wb: Write binary mode.r+: Read and write mode.a+: Append and read mode.
Exception Handling in File Operations
Always handle exceptions when working with files to avoid crashes due to missing files or permission issues.
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")
File Object Methods
File objects provide several useful methods:
read(): Reads the entire file.readline(): Reads a single line.readlines(): Reads all lines into a list.write(): Writes a string to the file.writelines(): Writes a list of strings to the file.seek(): Moves the file pointer to a specific position.tell(): Returns the current position of the file pointer.
with open("example.txt", "r+") as file:
file.seek(0) # Move to the beginning of the file
file.write("New content at the start.")
print("Current position:", file.tell())
Next: Modules