Python File Handling
File Handling in Python
File handling in Python refers to the process of creating, reading, writing, and manipulating files on the filesystem. Python provides built-in functions and methods to work with files efficiently, making it easy to handle text and binary data.
Opening a File
To work with a file in Python, you first need to open it using the open()
function. The syntax is:
file_name
: The name of the file you want to open (can include the path).mode
: A string indicating the mode in which the file is opened. Common modes include:'r'
: Read (default mode). Opens the file for reading.'w'
: Write. Opens the file for writing (creates a new file or truncates an existing one).'a'
: Append. Opens the file for writing (creates a new file or appends to an existing one).'b'
: Binary mode. Used for binary files (e.g., images).'t'
: Text mode (default mode). Used for text files.
Closing a File
Always close the file after you're done to free up system resources using the close()
method:
File Handling Operations
1. Writing to a File
You can write to a file using the write()
or writelines()
methods.
Using the with
statement automatically closes the file after the block is executed, which is a best practice.
2. Reading from a File
To read from a file, use the read()
, readline()
, or readlines()
methods.
read(size)
: Reads the entire file or up tosize
bytes.readline()
: Reads a single line from the file.readlines()
: Reads all lines and returns a list of strings.
3. Appending to a File
To add new content to an existing file without overwriting it, open the file in append mode ('a'
).
4. Working with Binary Files
When dealing with binary files (like images), use binary mode ('rb'
for reading and 'wb'
for writing).
File Handling Exceptions
It's important to handle exceptions that may occur during file operations, such as file not found or permission errors. You can use try-except blocks for this purpose.
Summary
- Opening a File: Use the
open()
function with the appropriate mode. - Writing to a File: Use
write()
orwritelines()
methods to write data. - Reading from a File: Use
read()
,readline()
, orreadlines()
methods to read data. - Appending to a File: Open the file in append mode (
'a'
) to add new data. - Binary Files: Use binary modes for reading and writing binary data.
- Exception Handling: Use try-except blocks to handle file-related errors.
File handling is a fundamental aspect of programming, allowing you to persist data and work with external resources in your Python applications.