File handling
File Handling in Python
File handling in Python allows you to read from and write to files on your computer. Python provides built-in functions for working with files, and the most common methods for file handling are provided by the open()
, read()
, write()
, and close()
functions.
1. Opening a File
The first step in working with a file is to open it using the built-in open()
function. This function returns a file object, which provides methods to read, write, and manipulate the file.
file = open("filename.txt", "mode")
Modes for Opening a File:
"r"
: Read (default mode). Opens the file for reading. If the file doesn’t exist, it raises an error."w"
: Write. Opens the file for writing. If the file already exists, it overwrites it."a"
: Append. Opens the file for appending. If the file doesn’t exist, it creates a new file."b"
: Binary mode. Reads or writes the file in binary mode (e.g.,"rb"
,"wb"
)."x"
: Exclusive creation. Creates a new file, but raises an error if the file already exists."t"
: Text mode (default). Opens the file in text mode (you can specify this explicitly, but it’s the default).
Example:
file = open("example.txt", "r") # Open a file in read mode
2. Reading from a File
You can read the content of a file using several methods:
a. read()
The read()
method reads the entire content of the file at once.
file = open("example.txt", "r")
content = file.read() # Reads the entire file
print(content)
file.close()
b. readline()
The readline()
method reads one line at a time from the file.
file = open("example.txt", "r")
line1 = file.readline() # Reads the first line
print(line1)
file.close()
c. readlines()
The readlines()
method reads the entire file and returns a list, where each element is a line from the file.
file = open("example.txt", "r")
lines = file.readlines() # Returns a list of lines
for line in lines:
print(line)
file.close()
3. Writing to a File
There are different methods to write to a file, depending on the mode in which the file is opened.
a. write()
The write()
method is used to write a string to the file. If the file is in write or append mode, it will write the string to the file.
file = open("example.txt", "w") # Open in write mode
file.write("Hello, world!\n")
file.close()
b. writelines()
The writelines()
method is used to write a list of strings to a file. Each string is written to the file without any newline characters, so you need to manually add \n
if required.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("example.txt", "w")
file.writelines(lines) # Writes a list of strings to the file
file.close()
4. Closing the File
It’s important to close the file after performing operations on it. This ensures that resources are released and the file is saved properly.
file.close()
However, Python provides a more efficient way to handle file opening and closing using a with
statement, which automatically closes the file after the block of code is executed.
5. Using with
Statement (Context Manager)
The with
statement simplifies file handling. It ensures that the file is properly closed after the operations, even if an error occurs within the block.
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to explicitly call file.close()
The file is automatically closed when the code inside the with
block finishes executing.
6. File Modes in Detail
Here’s a summary of the common file modes:
Mode | Description |
---|---|
"r" | Read mode: Opens the file for reading (default mode). Raises an error if the file doesn't exist. |
"w" | Write mode: Opens the file for writing. If the file exists, it is overwritten. If the file doesn't exist, it creates a new one. |
"a" | Append mode: Opens the file for writing. If the file exists, data is appended to the end. If it doesn’t exist, a new file is created. |
"x" | Exclusive creation: Creates a new file. If the file already exists, an error is raised. |
"b" | Binary mode: Used for reading/writing binary files (e.g., "rb" , "wb" ). |
"t" | Text mode (default): Used for reading/writing text files. |
Example of Opening a File in Append Mode:
with open("example.txt", "a") as file:
file.write("This is a new line appended to the file.\n")
7. File Operations and Handling Exceptions
It's good practice to handle potential errors when dealing with files, such as when a file doesn't exist or you don’t have permission to access it. You can use try-except blocks for this.
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You do not have permission to read this file.")
8. Example: Reading, Writing, and Appending to a File
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a file handling example.\n")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print("File content:")
print(content)
# Appending to a file
with open("example.txt", "a") as file:
file.write("Appended line: Learning file handling.\n")
# Reading again to see the changes
with open("example.txt", "r") as file:
content = file.read()
print("Updated file content:")
print(content)
Output:
File content:
Hello, Python!
This is a file handling example.
Updated file content:
Hello, Python!
This is a file handling example.
Appended line: Learning file handling.
9. Working with Binary Files
You can open and handle binary files (e.g., images, videos, etc.) using the "b"
mode. This is useful for non-text files.
Example: Reading and Writing a Binary File
# Writing a binary file
with open("example.bin", "wb") as file:
file.write(b'\xDE\xAD\xBE\xEF') # Writing bytes
# Reading a binary file
with open("example.bin", "rb") as file:
data = file.read()
print(data)
Output:
b'\xde\xad\xbe\xef'
10. Working with Directories
Python also allows you to handle directories (create, delete, list files) using the os
and shutil
modules.
import os
# Create a directory
os.mkdir("new_folder")
# List files in a directory
files = os.listdir(".")
print(files)
# Remove a directory
os.rmdir("new_folder")
Summary
- Opening a file: Use
open()
with different modes (r
,w
,a
,b
, etc.). - Reading from a file: Use
read()
,readline()
, orreadlines()
methods. - Writing to a file: Use
write()
orwritelines()
to write text to a file. - Closing a file: Always close files after use or use
with
for automatic closing. - Error handling: Use
try-except
blocks to handle potential errors (e.g.,FileNotFoundError
). - Binary files: Use
"b"
mode for binary files. - Directory operations: Use the
os
module to create, list, and delete directories.