Python6 min read
Python File Handling
Read from and write to files in Python.
Emily Davis
December 18, 2025
0.0k0
Work with files.
Write to File
```python # Write mode (creates new file) file = open("notes.txt", "w") file.write("Hello from San Diego!") file.close()
Better way - auto closes with open("notes.txt", "w") as file: file.write("Hello from San Diego!") ```
Read from File
```python # Read entire file with open("notes.txt", "r") as file: content = file.read() print(content)
Read line by line with open("notes.txt", "r") as file: for line in file: print(line) ```
Append to File
```python # Add to existing file with open("notes.txt", "a") as file: file.write("\nNew line added!") ```
Check if File Exists
```python import os
if os.path.exists("notes.txt"): print("File exists!") else: print("File not found") ```
Handle Errors
```python try: with open("data.txt", "r") as file: content = file.read() except FileNotFoundError: print("File doesn't exist!") ```
Remember
- Use 'with' statement - Always close files - Handle file errors
#Python#Beginner#Files