Python File Handling
Python provides several built-in functions for file handling, enabling us to create, read, update, and delete files.
Working with files is essential for many programming tasks, such as storing data, logging information, or reading configuration files. Python's file handling capabilities make it simple to work with files. Whether you're reading from, writing to,
or appending to a file, Python provides efficient and straightforward methods. Utilizing the with
statement ensures proper resource management, making it the recommended approach for file handling.
In this section, we'll explore how to handle files using Python.
Opening a File
The open()
function is used to open a file in Python. It takes two arguments:
the file name and the mode in which the file should be opened. The most commonly used modes are:
'r'
: Read mode (default) - Opens a file for reading.'w'
: Write mode - Opens a file for writing (creates a new file if it doesn't exist).'a'
: Append mode - Opens a file for appending new content to the end of the file.'b'
: Binary mode - Used with other modes to handle binary files.
1. Reading from a File
file = open('sample.txt', 'r')
content = file.read()
print(content)
file.close()
Output
Writing to a File
To write to a file, we use the 'w'
mode. This will overwrite the file if it already exists.
2. Writing to a File
file = open('output.txt', 'w')
file.write('Hello, this is a test file!')
file.close()
Output
Appending to a File
Use the 'a'
mode to append new content to an existing file.
3. Appending to a File
file = open('output.txt', 'a')
file.write('\nAdding a new line to the file.')
file.close()
Output
Using with
Statement
The with
statement is used to automatically handle file closing after its suite finishes.
This is the preferred way of working with files in Python as it ensures proper resource management.
4. Using the with
Statement
with open('sample.txt', 'r') as file:
content = file.read()
print(content)
Output
Common File Methods
- file.read(size): Reads specified number of characters from the file.
- file.readline(): Reads a single line from the file.
- file.readlines(): Reads all lines from the file and returns a list.
- file.write(text): Writes the given text to the file.
- file.close(): Closes the file.