File Handling in Python
? File Handling in Python
File handling in Python allows you to read from, write to, and manipulate files on your computer. Python provides built-in functions for file operations, such as opening, reading, writing, and closing files.
Here’s a breakdown of how to handle files in Python:
? 1. Opening Files
To work with files, you first need to open the file using the built-in open() function. The syntax is:
file_object = open("filename", "mode")filename: The name of the file you want to open (with the file extension).mode: The mode in which to open the file (e.g., read, write, append).
File Modes:
'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 doesn’t exist, it creates it. If the file exists, it overwrites the content.'a': Append – Opens the file for writing but appends data to the end of the file. If the file doesn’t exist, it creates it.'rb': Read in binary mode – Opens the file for reading in binary format.'wb': Write in binary mode – Opens the file for writing in binary format.'r+': Read and write – Opens the file for both reading and writing.'a+': Append and read – Opens the file for both appending and reading.
? 2. Reading Files
Once the file is opened in read mode ('r'), you can read its contents using various methods.
1. read()
Reads the entire file content as a string.
file = open("example.txt", "r")content = file.read()print(content)file.close()2. readline()
Reads a single line from the file.
file = open("example.txt", "r")line = file.readline()print(line)file.close()3. readlines()
Reads all the lines in the file and returns a list of lines.
file = open("example.txt", "r")lines = file.readlines()print(lines)file.close()? 3. Writing to Files
To write to a file, you need to open it in write ('w'), append ('a'), or write and read ('r+') mode.
1. write()
Writes a string to the file.
file = open("example.txt", "w")file.write("Hello, world!\n")file.write("This is a second line.\n")file.close()If the file already exists, the content will be overwritten.
If the file doesn’t exist, it will be created.
2. writelines()
Writes a list of strings to the file.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]file = open("example.txt", "w")file.writelines(lines)file.close()? 4. Appending to Files
To append data to an existing file, you can use the 'a' mode.
file = open("example.txt", "a")file.write("This is a new line added.\n")file.close()? 5. Closing Files
After performing file operations, it's important to close the file to free up resources.
file = open("example.txt", "r")content = file.read()file.close()Always close the file after reading or writing to ensure that changes are saved, and the file is properly released.
? 6. Using with Statement
Python’s with statement simplifies file handling by automatically closing the file after the block of code is executed. This ensures that the file is always closed properly, even if an error occurs.
with open("example.txt", "r") as file: content = file.read() print(content)# No need to manually call file.close()This method eliminates the need to explicitly call
file.close().
? 7. File Handling with Binary Files
Python can also handle binary files, such as images and videos, by opening the file in binary mode ('rb' for reading and 'wb' for writing).
Example: Reading a Binary File (Image)
with open("example.jpg", "rb") as file: content = file.read() print(content[:50]) # Display the first 50 bytes of the binary contentExample: Writing to a Binary File
data = b'\x89PNG\r\n\x1a\n...'with open("new_image.png", "wb") as file: file.write(data)? 8. Error Handling in File Handling
File operations can raise exceptions, such as when a file does not exist, or there are permission issues. You can handle these exceptions using try...except.
Example: Handling FileNotFoundError
try: file = open("non_existent_file.txt", "r") content = file.read()except FileNotFoundError: print("The file does not exist.")finally: # No need to worry about closing the file because the code never reached the `open` function pass? 9. Summary of File Handling Methods
File Operations:
open(filename, mode): Opens a file.read(): Reads the entire file.readline(): Reads a single line from the file.readlines(): Reads all lines and returns them as a list.write(string): Writes a string to the file.writelines(list): Writes a list of strings to the file.close(): Closes the file.
File Modes:
'r': Read.'w': Write (overwrite).'a': Append.'rb': Read in binary mode.'wb': Write in binary mode.'r+': Read and write.'a+': Append and read.
Best Practices:
Always close the file using
file.close().Prefer using the
withstatement for automatic file closure.Handle exceptions, such as
FileNotFoundError, usingtry...except.
File handling is essential for many programs that need to interact with external data. If you have any specific questions or need further examples, feel free to ask! ?