To read from files and write to files in Python. we can use the `open()` method.
open() method is a built-in method in Python, which allows us to open a file in different modes (e.g., "read mode", "write mode", "append mode").
How we can read from and write to files:
The open() function accepts two arguments, the first argument is the file path location and the second argument is a mode in which the file needs to be open. for reading mode, we use the `r` character.
# Open the file in read mode with open("sample.txt", "r") as file: # Read the entire content of the file content = file.read() print(content) # We can also read line by line with open("sample.txt", "r") as file: for line in file: print(line.strip()) # strip() removes any leading or trailing whitespace
The open() function accepts two arguments, the first argument is the file path location and the second argument is a mode in which the file needs to be open. for writing mode, we use the `w` character.
# Open the file in write mode (this will overwrite the existing content) with open("sample.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new line.") # We can also use the print function to write to a file with open("sample.txt", "w") as file: print("Hello, World!", file=file) print("This is a new line.", file=file)
open() function accepts two arguments, the first argument is the file path location and the second argument is a mode in which the file needs to be open. for appending mode, we use the `a` character.
# Open the file in append mode with open("sample.txt", "a") as file: file.write("\nThis is a new line appended.")
It's essential to handle exceptions when working with files to deal with potential errors, such as file not found or insufficient permissions.
try: with open("sample.txt", "r") as file: content = file.read() print(content) except FileNotFoundError: print("File not found!") except PermissionError: print("Permission denied!") except Exception as e: print("An error occurred:", e)
Always ensure that we "close" the file after we finish working with it, using with statement as shown in the above examples, which automatically closes the file when the block is exited.
with open("sample.txt", "r") as file: content = file.read() print(content)
This is a common and safe way to work with files in Python as it ensures that the file is properly closed after use, even if an error occurs within the block.