In Python, file handling refers to reading and writing data to files. Here are some common operations and functions related to file handling in Python:
- Opening a File: To open a file, you can use the
open()function and specify the file name and mode (read, write, append, etc.).file = open("myfile.txt", "r")# Opens the file in read mode
- Reading from a File: Once a file is opened, you can read its contents using methods like
read(),readline(), orreadlines().pythonCopy code- content = file.read() # Reads the entire file content
- line = file.readline() # Reads a single line from the file
- lines = file.readlines() # Reads all lines and returns a list
- Writing to a File: To write data to a file, you need to open it in write mode (
"w") or append mode ("a"), and then use thewrite()method.file = open("myfile.txt", "w") # Opens the file in write mode file.write("Hello, World!") # Writes data to the filefile.close() # Closes the file
- Appending to a File: If you want to add content to an existing file without overwriting its contents, open the file in append mode (
"a") and use thewrite()method.file = open("myfile.txt", "a") # Opens the file in append mode file.write("New content") # Appends data to the filefile.close() # Closes the file
- Closing a File: It’s important to close the file after you’re done with it to release system resources.
file.close()# Closes the file
- Using Context Managers (Recommended): A better practice is to use the
withstatement, which automatically closes the file after the block of code.with open("myfile.txt", "r") as file:content = file.read()# File is automatically closed outside the 'with' block
- Error Handling: When working with files, errors can occur. To handle exceptions, you can use
tryandexceptblocks.- try:
- file = open(“myfile.txt”, “r”)
- # Perform file operations
- except FileNotFoundError:
- print(“File not found!”)
- finally:
- file.close() # Close the file regardless of an exception
These are some of the fundamental file handling operations in Python. It’s important to handle file operations properly, close files after use, and handle potential exceptions to ensure clean and error-free file handling.