Python Exception Handling
0 117
File handling is a crucial aspect of programming that allows developers to interact with files stored on a system. Python provides a simple and efficient way to perform operations like creating, reading, writing, and closing files, making it easier to manage data persistence.
Opening a File
In Python, the open()
function is used to open a file. It requires the file name and the mode in which the file should be opened.
file = open('example.txt', 'r')
Here, 'example.txt'
is the name of the file, and 'r'
denotes the read mode.
File Modes
Different modes can be used with the open()
function to specify the operation:
'r'
: Read mode (default). Opens the file for reading.'w'
: Write mode. Creates a new file or truncates existing file.'a'
: Append mode. Adds data to the end of the file.'b'
: Binary mode. Used for binary files.'+'
: Update mode. Allows reading and writing.
Reading from a File
Python provides several methods to read data from a file:
read()
: Reads the entire file.readline()
: Reads one line at a time.readlines()
: Reads all lines and returns them as a list.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing to a File
To write data to a file, use the write()
or writelines()
methods:
with open('example.txt', 'w') as file:
file.write("Hello, World!")
This will write "Hello, World!" to example.txt
, creating the file if it doesn't exist or overwriting it if it does.
Appending to a File
To add data to the end of an existing file without overwriting its content, use append mode:
with open('example.txt', 'a') as file:
file.write("\nAppended line.")
Closing a File
It's important to close a file after performing operations to free up system resources. Using the with
statement, as shown above, ensures that the file is automatically closed after the block is executed.
Handling Exceptions
When working with files, it's good practice to handle exceptions to prevent the program from crashing due to unforeseen errors:
try:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")
Conclusion
File handling in Python is straightforward and powerful, allowing developers to perform a wide range of file operations with ease. By understanding the various modes and methods available, one can efficiently manage file I/O tasks in Python applications.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments