File handling is a crucial skill in Python programming. Below are key points and best practices to ensure safe and efficient file operations.
with open()
to handle files, which automatically closes the file after use.'r'
(read), 'w'
(write), 'a'
(append), 'b'
(binary), and '+'
(read/write).utf-8
) when reading/writing text files to avoid encoding errors.FileNotFoundError
and IOError
.os.path
or pathlib
for cross-platform path handling.'w'
, as it overwrites existing files.tempfile
module for creating temporary files and directories safely.file.close()
.with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
try:
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, world!")
except IOError as e:
print("File error:", e)
from pathlib import Path
file_path = Path('example.txt')
if file_path.exists():
print("File exists.")
with open('large_file.txt', 'r') as file:
for line in file:
print(line.strip())
with open('log.txt', 'a') as file:
file.write("New log entry\n")
import tempfile
with tempfile.TemporaryFile() as temp_file:
temp_file.write(b'Hello temp')
temp_file.seek(0)
print(temp_file.read())
import os
filepath = 'example.txt'
if os.access(filepath, os.W_OK):
print("File is writable")
import os
os.rename('oldname.txt', 'newname.txt')
import os
try:
os.remove('tempfile.txt')
except FileNotFoundError:
print("File not found.")
import json
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)