๐ Python File Handling โ Read, Write, and Append Files
Python file handling covers reading, writing, and appending data. The 'with' statement ensures files are always closed properly.
Use pathlib.Path instead of os.path โ it's more readable and has a cleaner API for path operations.
๐ป Code Example:
# โโ Reading a file โโโโโโโโโโโโโโโโโโโโโโโโโโโ with open('pynfinity_notes.txt', 'r', encoding='utf-8') as f: content = f.read() # Read entire file as string # OR # lines = f.readlines() # Read into list of lines # for line in f: # Memory-efficient iteration # print(line.strip()) # โโ Writing a file (overwrites!) โโโโโโโโโโโโโ with open('output.txt', 'w', encoding='utf-8') as f: f.write("Pynfinity โ The Infinite Python Hub\n") f.write("Author: santoshtvk\n") # โโ Appending to a file โโโโโโโโโโโโโโโโโโโโโโโ with open('output.txt', 'a', encoding='utf-8') as f: f.write("New entry added by tvk\n") # โโ JSON file read/write โโโโโโโโโโโโโโโโโโโโโโ import json # Write JSON data = {'platform': 'pynfinity', 'users': 1000, 'premium': True} with open('config.json', 'w') as f: json.dump(data, f, indent=4) # Read JSON with open('config.json', 'r') as f: loaded = json.load(f) print(loaded['platform']) # pynfinity # โโ Check if file exists โโโโโโโโโโโโโโโโโโโโโ from pathlib import Path if Path('pynfinity_notes.txt').exists(): print("File found!")
| Concept | Key Takeaway |
|---|---|
| 'r' | Read โ file must exist |
| 'w' | Write โ creates or OVERWRITES file |
| 'a' | Append โ adds to end of existing file |
| 'rb' / 'wb' | Binary mode โ for images, PDFs, etc. |
| f.read() | Reads entire file as one string |
| f.readlines() | Returns list where each item is one line |
Keep exploring and happy coding! ๐