1. Opening Files
f = open("file.txt", "r") # Read mode (default)
f = open("file.txt", "w") # Write mode (overwrites)
f = open("file.txt", "a") # Append mode
f = open("file.txt", "rb") # Read binary
f = open("file.txt", "r+", encoding="utf-8") # Read/Write with encoding
2. Reading from Files
content = f.read() # Read entire file
line = f.readline() # Read one line
lines = f.readlines() # Read all lines into a list
# Read line-by-line
for line in f:
print(line.strip())
3. Writing to Files
f.write("Hello, world!") # Write a string
f.writelines(["Line 1\n", "Line 2\n"]) # Write a list of lines
4. File Context Management (with with
)
with open("file.txt", "r") as f:
content = f.read()
# File is automatically closed
5. File Modes Summary
"r"
– Read (default)
"w"
– Write (overwrite)
"a"
– Append
"r+"
– Read and write
"b"
– Binary mode (combine with others like "rb"
)
"x"
– Create a new file (error if it exists)
6. Checking File Existence
import os
if os.path.exists("file.txt"):
print("File exists")
7. Deleting Files
import os
os.remove("file.txt")
8. Working with Directories
import os
os.mkdir("new_folder") # Create a directory
os.rmdir("new_folder") # Remove an empty directory
os.listdir(".") # List files in current directory
os.getcwd() # Get current working directory
os.chdir("/path/to/dir") # Change directory
9. Handling File Exceptions
try:
with open("file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found")
except IOError:
print("IO error occurred")