🐍 Python Tutorial: File Handling
File handling in Python allows you to work with files to read, write, and modify data stored in them. Python provides simple yet powerful functions to manage files effectively.
1. Reading Files
Use the open() function to read from a file. Make sure the file exists:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()You can also read line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())2. Writing to Files
Use mode "w" to overwrite a file or "a" to append to it:
with open("example.txt", "w") as file:
file.write("Hello, world!
")
file.write("Writing to a file in Python.")Appending:
with open("example.txt", "a") as file:
file.write("
Appending this line.")3. File Modes
Common modes used with open():
"r": Read (default, file must exist)"w": Write (creates or truncates file)"a": Append (creates file if it doesn't exist)"b": Binary mode"+": Read and write
4. Handling Errors
Always handle errors when working with files to prevent crashes:
try:
with open("nonexistent.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("The file was not found.")