Python - File Handling
File handling is a critical aspect of programming that allows you to create, read, write, and manipulate files. Python provides simple and efficient methods for file handling through its built-in functions and the open() function.
Opening a File
To handle a file in Python, the first step is to open it using the open() function. The syntax is:
open(file, mode)
Modes for Opening Files
Mode Description
'r' Read mode (default). Opens a file for reading.
'w' Write mode. Creates a new file or overwrites an existing one.
'a' Append mode. Adds content to the end of the file.
'x' Exclusive creation. Fails if the file already exists.
'b' Binary mode. Reads/writes binary data.
't' Text mode (default). Reads/writes text.
'+' Read and write mode.
Reading from a File
Example: Reading Entire File
# Open the file in read mode
file = open("example.txt", "r")
# Read the file's content
content = file.read()
print(content)
# Close the file
file.close()
Example: Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Methods for Reading
read(): Reads the entire file.
readline(): Reads a single line.
readlines(): Returns a list of all lines.
Writing to a File
Example: Writing New Content
# Open the file in write mode
file = open("example.txt", "w")
# Write content to the file
file.write("This is a new file.\n")
file.write("Python file handling is easy!")
# Close the file
file.close()
Example: Appending Content
with open("example.txt", "a") as file:
file.write("\nAppending new content to the file.")
Checking File Existence
You can check whether a file exists before performing operations using the os module.
import os
if os.path.exists("example.txt"):
print("The file exists.")
else:
print("The file does not exist.")
Deleting a File
To delete a file, use the os.remove() method:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully.")
else:
print("File does not exist.")
Example: Combining File Operations
# Write to a file
with open("data.txt", "w") as file:
file.write("Hello, Python!\nThis is file handling.")
# Read the file
with open("data.txt", "r") as file:
print("File Content:\n", file.read())
# Append new content
with open("data.txt", "a") as file:
file.write("\nAppending new data.")
Advantages of Using with Statement
Using the with statement is preferred because it ensures that the file is properly closed, even if an exception occurs during file operations.
with open("example.txt", "r") as file:
content = file.read()
print(content)
File Handling Errors
Python provides the try-except block to handle file-related errors:
try:
with open("nonexistent.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found. Please check the filename.")
except Exception as e:
print(f"An error occurred: {e}")
Conclusion
Python makes file handling straightforward and efficient with its open() function and with statements. Whether you're reading data, writing logs, or processing large files, Python's tools are versatile enough to meet your needs. Proper error handling ensures your programs remain robust and reliable.