In Python, file handling is a simple yet powerful feature that allows users to create, read, write, and manage files. Compared to other programming languages, Python offers a streamlined approach to file handling. The data stored in files is non-volatile, meaning it can be accessed after the program has terminated, making file handling crucial when dealing with large datasets or permanent data storage.
1. Open the file
2. Perform the operation (read/write)
3. Close the file
To open a file in Python, the open() function is used. It requires two main arguments:
• File Name: The name of the file you want to access.
• Access Mode: The mode in which you want to open the file (e.g., read, write, append).
file_object = open(<file_name>, <access_mode>)
| Mode | Description |
|---|---|
| r | Opens a file for reading (default). The file pointer is at the beginning. |
| rb | Opens a file for reading in binary format. |
| r+ | Opens a file for reading and writing. The file pointer is at the beginning. |
| w | Opens a file for writing. It overwrites the file if it exists. |
| wb | Opens a file for writing in binary mode. |
| w+ | Opens a file for writing and reading. It overwrites the file if it exists. |
| a | Opens a file for appending. The file pointer is at the end. |
| x | Creates a new file. It raises an error if the file already exists. |
fileptr = open("file.txt", "r")
if fileptr:
print("File opened successfully")
It’s essential to close a file after performing operations to free up system resources. Use the close() method to close the file.
fileptr.close()
Alternatively, you can use the with statement, which automatically closes the file after the operations are completed.
with open("file.txt", "r") as fileptr:
data = fileptr.read()
print(data)
# No need to explicitly close the file
To read the contents of a file, Python offers several methods:
• read(): Reads the entire file or a specified number of characters.
• readline(): Reads a single line from the file.
• readlines(): Reads all the lines and returns them as a list.
with open("file.txt", "r") as fileptr:
print(fileptr.read()) # Reads the whole file
print(fileptr.readline()) # Reads one line
print(fileptr.readlines()) # Returns all lines as a list
To write data into a file, open it in write or append mode. If the file doesn’t exist, Python will create it.
with open("file.txt", "w") as fileptr:
fileptr.write("Hello, World!")
with open("file.txt", "a") as fileptr:
fileptr.write("\nAppended text")
The seek() method allows you to move the file pointer to a specific location, while tell() returns the current position of the file pointer.
with open("file.txt", "r") as fileptr:
print(fileptr.tell()) # Current position
fileptr.seek(5) # Move pointer to 5th byte
print(fileptr.read()) # Reads from 5th byte
onwards
The os module in Python allows interaction with the operating system for file-related operations, such as renaming and deleting files.
import os
os.rename("old_file.txt", "new_file.txt")
import os
os.remove("file.txt")
| Method | Description |
|---|---|
| file.close() | Closes the opened file. |
| file.read() | Reads the file content. |
| file.write() | Writes data to the file. |
| file.seek() | Moves the file pointer to a specific position. |
| file.tell() | Returns the current position of the file pointer. |
| file.readlines() | Returns a list of lines in the file. |
Python file handling simplifies working with files. It allows for efficient file manipulation, including reading, writing, appending, and modifying file pointers. With features like the with statement and the os module, Python provides a robust environment for managing files across different platforms.