File I/O (Reading & Writing Files)

Introduction

ဒီ chapter မှာတော့ file တွေ နဲ့ ဘယ်လို အလုပ်လုပ်ရမလဲဆိုတာ တွေ့ရပါမယ်။

File I/O ဆိုတာ Input/Output ပေါ့။ file ကနေ data ဖတ်တာ (Input) နဲ့ file ထဲကို data ရေးတာ (Output)။

Real-world မှာ program တွေက file တွေနဲ့ အမြဲ အလုပ်လုပ်ရတယ်။ ဥပမာ:

  • Configuration file တွေ ဖတ်တာ
  • Log file တွေ ရေးတာ
  • User data တွေ သိမ်းတာ
  • CSV, JSON file တွေ process လုပ်တာ
  • Image, Video file တွေ ကူးတာ

Python မှာ file တွေနဲ့ အလုပ်လုပ်တာက အရမ်းလွယ်တယ်။ စကြမယ်။

File Modes (File ကိုဖွင့်မယ့် ပုံစံတွေ)

File တစ်ခုကို ဖွင့်တဲ့အခါ mode ကို သတ်မှတ်ပေးရတယ်။ Mode က file ကို ဘယ်လို သုံးမလဲ ပြောတာ။

Basic Modes:

Basic File Modes
# 'r' - Read mode (Default) # File ကို ဖတ်ဖို့ပဲ ဖွင့်တယ် # File မရှိရင် FileNotFoundError တက်မယ် # 'w' - Write mode # File ကို ရေးဖို့ ဖွင့်တယ် # File ရှိပြီးသားဆို အကုန် ဖျက်ပြီး အသစ် ရေးမယ် # File မရှိရင် အသစ် ဆောက်မယ် # 'a' - Append mode # File ရဲ့ နောက်ဆုံးမှာ ဆက်ရေးမယ် # data အဟောင်းတွေ မပျက်ဘူး # File မရှိရင် အသစ် ဆောက်မယ် # 'x' - Exclusive creation # File အသစ် ဆောက်မယ် # File ရှိပြီးသားဆို FileExistsError တက်မယ်

Advanced Modes:

Advanced File Modes
# 'r+' - Read and Write # ဖတ်လို့လည်း ရ၊ ရေးလို့လည်း ရ # File မရှိရင် error တက်မယ် # 'w+' - Write and Read # ရေးလို့လည်း ရ၊ ဖတ်လို့လည်း ရ # File ရှိပြီးသားဆို အကုန် ဖျက်မယ် # 'a+' - Append and Read # နောက်ဆုံးမှာ ဆက်ရေးလို့ရ၊ ဖတ်လို့လည်း ရ # 'b' - Binary mode # Text မဟုတ်ဘဲ binary (bytes) အနေနဲ့ # 'rb', 'wb', 'ab' စသဖြင့် တွဲသုံးတယ် # 't' - Text mode (Default) # Text file တွေအတွက် (ရေးစရာမလို)

Mode Examples:

mode_examples.py
# Example 1: Read mode ('r') try: f = open("test.txt", "r") content = f.read() f.close() except FileNotFoundError: print("File မရှိဘူး") # Example 2: Write mode ('w') - အရင် data ဖျက်မယ် f = open("output.txt", "w") f.write("အသစ် ရေးမယ်") f.close() # Example 3: Append mode ('a') - နောက်မှာဆက်ရေးမယ် f = open("output.txt", "a") f.write("\nနောက်မှာဆက်မယ်") f.close() # Example 4: Exclusive creation ('x') try: f = open("new_file.txt", "x") f.write("အသစ် file") f.close() except FileExistsError: print("File ရှိပြီးသား")
အရေးကြီး:
  • w mode က file ရှိပြီးသားဆို အကုန် ဖျက်ပြီး အသစ် ရေးမယ်
  • a mode က data အဟောင်းကို မဖျက်ပဲ နောက်မှာဆက်ရေးတယ်
  • x mode က file ရှိပြီးသားဆို error တက်မယ်

Context Manager (with statement)

File ဖွင့်ပြီးရင် close() လုပ်ဖို့ မမေ့သင့်ဘူး။ မလုပ်ရင် memory leak ဖြစ်နိုင်တယ်။

ဒါကြောင့် with statement ကို သုံးသင့်တယ်။ သူက file ကို အလိုလို close လုပ်ပေးတယ်။

Manual Close (Not Recommended):

manual_close.py
# Not recommended - close() မေ့နိုင်တယ် f = open("test.txt", "r", encoding="utf-8") content = f.read() f.close() # ဒါကို မေ့ရင် problem print(content)

With Statement (Recommended):

with_statement.py
# Recommended - အလိုလို close လုပ်ပေးတယ် with open("test.txt", "r", encoding="utf-8") as f: content = f.read() print(content) # ဒီ with block ကနေ ထွက်တာနဲ့ file အလိုလို close ဖြစ်သွားတယ်

Why Use Context Manager?

context_manager_benefit.py
# Error ဖြစ်လည်း file close ဖြစ်တယ် try: with open("test.txt", "r") as f: content = f.read() # ဒီမှာ error တက်လည်း file close ဖြစ်သွားမယ် result = 10 / 0 # ZeroDivisionError except ZeroDivisionError: print("Error တက်ပေမယ့် file close ဖြစ်ပြီးပြီ")
အကြံပေးချင်တာက: အမြဲတမ်း with open() as f: ကို သုံးစေချင်တယ်။ Manual close() မသုံးသင့်။

Reading Text Files

Text file တွေ ဖတ်ဖို့ နည်းလမ်းတွေ အများကြီး ရှိတယ်။

Method 1: read() - All at Once

read_all.py
# File တစ်ခုလုံးကို တစ်ခါတည်း ဖတ်မယ် with open("sample.txt", "r", encoding="utf-8") as f: content = f.read() print(content) print(f"Type: {type(content)}") # str print(f"Length: {len(content)} characters")

Method 2: readline() - Line by Line

read_line.py
# တစ်ကြောင်းချင်း ဖတ်မယ် with open("sample.txt", "r", encoding="utf-8") as f: line1 = f.readline() line2 = f.readline() line3 = f.readline() print(f"Line 1: {line1}") print(f"Line 2: {line2}") print(f"Line 3: {line3}")

Method 3: readlines() - All Lines as List

read_lines.py
# list အဖြစ် ပြန်ပေးမယ် with open("sample.txt", "r", encoding="utf-8") as f: lines = f.readlines() print(f"Type: {type(lines)}") # list print(f"Total lines: {len(lines)}") for i, line in enumerate(lines, 1): print(f"Line {i}: {line.strip()}") # strip() က \n ဖြုတ်ပေးတယ်

Method 4: Iterating (Memory Efficient)

iterate_lines.py
# Best for large files - Memory efficient with open("large_file.txt", "r", encoding="utf-8") as f: for line_number, line in enumerate(f, 1): print(f"{line_number}: {line.strip()}") # Condition ပေါ်မူတည်ပြီး ရပ်လို့ရတယ် if line_number == 10: break

Comparison: read() vs readlines() vs Iteration

reading_comparison.py
# read() - File အသေးလေးတွေအတွက် ကောင်းတယ် with open("small.txt", "r") as f: content = f.read() # readlines() - File အသေးတွေအတွက် ကောင်းတယ် with open("small.txt", "r") as f: lines = f.readlines() # Iteration - File ကြီးတွေအတွက် အကောင်းဆုံး with open("huge.txt", "r") as f: for line in f: # တစ်ကြောင်းချင်း process လုပ်တယ် pass # Memory efficient!

Writing Text Files

File ထဲကို data ရေးဖို့ write() နဲ့ writelines() သုံးတယ်။

Method 1: write() - Single String

write_single.py
# write() က string တစ်ခု ရေးတယ် with open("output.txt", "w", encoding="utf-8") as f: f.write("ဒါက ပထမကြောင်း\n") f.write("ဒါက ဒုတိယကြောင်း\n") f.write("ဒါက တတိယကြောင်း") print("ရေးပြီးပြီ")

Method 2: writelines() - List of Strings

write_multiple.py
# writelines() က list ကို ရေးတယ် lines = [ "Python က လွယ်တယ်\n", "JavaScript လည်းပျော်စရာကောင်းတယ်\n", "C++ က အလွယ်ဆုံး 😂\n" ] with open("languages.txt", "w", encoding="utf-8") as f: f.writelines(lines) print("ရေးပြီးပြီ")

Append Mode Example:

append_mode.py
# အရင် file ကို ဖျက်မယ် (w mode) with open("log.txt", "w", encoding="utf-8") as f: f.write("Log started\n") # နောက်မှာဆက်ရေးမယ် (a mode) with open("log.txt", "a", encoding="utf-8") as f: f.write("User logged in\n") f.write("User performed action\n") f.write("User logged out\n") # ဖတ်ကြည့်မယ် with open("log.txt", "r", encoding="utf-8") as f: print(f.read())

Writing with f-strings:

write_formatted.py
name = "မောင်မောင်" age = 25 city = "Yangon" with open("profile.txt", "w", encoding="utf-8") as f: f.write(f"Name: {name}\n") f.write(f"Age: {age}\n") f.write(f"City: {city}\n") print("Profile သိမ်းပြီး")

Working with Binary Files

Image, audio, video, PDF စတဲ့ binary file တွေအတွက် b mode သုံးရတယ်။

Critical: Binary mode မှာ encoding parameter မသုံးဘူး။ Binary က bytes ပဲ၊ text မဟုတ်ဘူး။

Reading Binary Files:

read_binary.py
# Image file ဖတ်မယ် with open("photo.jpg", "rb") as f: binary_data = f.read() print(f"Type: {type(binary_data)}") # bytes print(f"Size: {len(binary_data)} bytes") print(f"First 10 bytes: {binary_data[:10]}")

Writing Binary Files:

write_binary.py
# Binary data ရေးမယ် binary_data = b'\x89PNG\r\n\x1a\n' # PNG header with open("test.png", "wb") as f: f.write(binary_data)

Copying Binary Files:

copy_binary.py
# Image copy လုပ်မယ် with open("original.jpg", "rb") as source: with open("copy.jpg", "wb") as destination: destination.write(source.read()) print("Copy လုပ်ပြီးပြီ")

Efficient Large File Copying:

copy_large_binary.py
# Large file တွေအတွက် chunk လိုက် copy ကူးမယ် chunk_size = 4096 # 4 KB with open("large_video.mp4", "rb") as source: with open("copy_video.mp4", "wb") as destination: while True: chunk = source.read(chunk_size) if not chunk: break destination.write(chunk) print("Large file copy ကူးပြီးပြီ")

Working with CSV Files

CSV (Comma-Separated Values) က spreadsheet data ကို simple text format အဖြစ် သိမ်းတာ။

Reading CSV (Basic):

read_csv_basic.py
import csv # CSV file ဖတ်မယ် with open("data.csv", "r", encoding="utf-8") as f: csv_reader = csv.reader(f) for row in csv_reader: print(row) # List အဖြစ် ရမယ်

Reading CSV with Headers:

read_csv_headers.py
import csv # DictReader က header row ကို key အဖြစ် သုံးတယ် with open("students.csv", "r", encoding="utf-8") as f: csv_reader = csv.DictReader(f) for row in csv_reader: print(f"Name: {row['name']}, Age: {row['age']}")

Writing CSV (Basic):

write_csv_basic.py
import csv data = [ ["Name", "Age", "City"], ["မောင်စိုင်း", 25, "Yangon"], ["အကိတ်", 23, "Mandalay"], ["အညာ", 30, "Bagan"] ] with open("people.csv", "w", encoding="utf-8", newline="") as f: csv_writer = csv.writer(f) csv_writer.writerows(data) print("CSV ရေးပြီးပြီ")

Writing CSV with DictWriter:

write_csv_dict.py
import csv # Dictionary list students = [ {"name": "မောင်မောင်", "age": 20, "grade": "A"}, {"name": "အကိတ်", "age": 21, "grade": "B"}, {"name": "အညာ", "age": 22, "grade": "A"} ] # DictWriter သုံးမယ် with open("students.csv", "w", encoding="utf-8", newline="") as f: fieldnames = ["name", "age", "grade"] csv_writer = csv.DictWriter(f, fieldnames=fieldnames) csv_writer.writeheader() # Header row ရေးမယ် csv_writer.writerows(students) # Data rows ရေးမယ် print("Students CSV ရေးပြီးပြီ")

Handling Different Delimiters:

csv_delimiters.py
import csv # Tab-separated values (TSV) with open("data.tsv", "r") as f: csv_reader = csv.reader(f, delimiter="\t") for row in csv_reader: print(row) # Semicolon-separated values with open("data.txt", "r") as f: csv_reader = csv.reader(f, delimiter=";") for row in csv_reader: print(row) # Pipe-separated values with open("data.psv", "r") as f: csv_reader = csv.reader(f, delimiter="|") for row in csv_reader: print(row)

Complete CSV Example:

csv_complete_example.py
import csv # Write grades grades = [ {"student": "မောင်မောင်", "python": 95, "javascript": 88}, {"student": "အကိတ်", "python": 92, "javascript": 90}, {"student": "အညာ", "python": 88, "javascript": 85} ] with open("grades.csv", "w", encoding="utf-8", newline="") as f: fieldnames = ["student", "python", "javascript"] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(grades) # Read and calculate average with open("grades.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) print("Student Grades:") for row in reader: python = int(row["python"]) javascript = int(row["javascript"]) average = (python + javascript) / 2 print(f"{row['student']}: Python={python}, JS={javascript}, Avg={average}")

Working with JSON Files

JSON (JavaScript Object Notation) က web API တွေမှာ အသုံးအများဆုံး data format။

JSON Basics:

json_basics.py
import json # Python dictionary data = { "name": "မောင်မောင်", "age": 25, "city": "Yangon", "skills": ["Python", "JavaScript", "SQL"] } # Dictionary ကို JSON string အဖြစ် ပြောင်းမယ် json_string = json.dumps(data) print(f"JSON string: {json_string}") print(f"Type: {type(json_string)}") # str

dumps() vs dump():

dumps_vs_dump.py
import json data = {"name": "Test", "value": 100} # dumps() - Dictionary → JSON string json_string = json.dumps(data) print(f"dumps() result: {json_string}") # dump() - Dictionary → JSON file with open("data.json", "w") as f: json.dump(data, f) print("dump() က file ထဲ တိုက်ရိုက် ရေးတယ်")

loads() vs load():

loads_vs_load.py
import json # loads() - JSON string → Dictionary json_string = '{"name": "Test", "value": 100}' data = json.loads(json_string) print(f"loads() result: {data}") print(f"Type: {type(data)}") # dict # load() - JSON file → Dictionary with open("data.json", "r") as f: data = json.load(f) print(f"load() result: {data}")

Pretty Printing with indent:

json_pretty_print.py
import json data = { "name": "မောင်မောင်", "age": 25, "skills": ["Python", "JavaScript"], "address": { "city": "Yangon", "country": "Myanmar" } } # Without indent - တစ်ကြောင်းတည်း print("Without indent:") print(json.dumps(data)) # With indent - လှတယ် print("\nWith indent=4:") print(json.dumps(data, indent=4)) # Save with pretty print with open("pretty.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=4)

Handling Non-ASCII Characters:

json_non_ascii.py
import json data = { "name": "မောင်မောင်", "city": "ရန်ကုန်" } # Default - Myanmar စာ escape ဖြစ်သွားမယ် print("Default (ensure_ascii=True):") print(json.dumps(data)) # ensure_ascii=False - Myanmar စာ မပျက်ဘူး print("\nWith ensure_ascii=False:") print(json.dumps(data, ensure_ascii=False)) # File ထဲ သိမ်းတဲ့အခါ ensure_ascii=False သုံးသင့်တယ် with open("myanmar.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=4)

Working with Nested JSON:

nested_json.py
import json # Complex nested structure company = { "name": "TechCorp", "employees": [ { "id": 1, "name": "မောင်မောင်", "position": "Developer", "skills": ["Python", "JavaScript"] }, { "id": 2, "name": "အကိတ်", "position": "Designer", "skills": ["Photoshop", "Illustrator"] } ], "departments": { "IT": {"head": "အညာ", "budget": 50000}, "HR": {"head": "အကိတ်မ", "budget": 30000} } } # Save nested JSON with open("company.json", "w", encoding="utf-8") as f: json.dump(company, f, ensure_ascii=False, indent=4) # Read and access nested data with open("company.json", "r", encoding="utf-8") as f: data = json.load(f) print(f"Company: {data['name']}") print(f"\nEmployees:") for emp in data["employees"]: print(f" {emp['name']} - {emp['position']}") print(f"\nIT Department Head: {data['departments']['IT']['head']}")

Complete JSON Example:

json_complete_example.py
import json def save_config(filename, config): """Config dictionary ကို JSON file အဖြစ် သိမ်းမယ်""" with open(filename, "w", encoding="utf-8") as f: json.dump(config, f, ensure_ascii=False, indent=4) print(f"Config သိမ်းပြီး: {filename}") def load_config(filename): """JSON file ကနေ config ဖတ်မယ်""" with open(filename, "r", encoding="utf-8") as f: return json.load(f) # Example usage config = { "app_name": "My App", "version": "1.0.0", "settings": { "theme": "dark", "language": "my", "notifications": True } } save_config("app_config.json", config) loaded_config = load_config("app_config.json") print(f"Loaded config: {loaded_config}")

File System Operations

File content တွေကို ဖတ်/ရေး တာချည်းပဲမဟုတ် file system နဲ့လည်း အလုပ်လုပ်လို့ရတယ်။

Using os Module:

os_basic.py
import os # လက်ရှိ working directory current_dir = os.getcwd() print(f"Current directory: {current_dir}") # Directory ထဲက file တွေ list လုပ်မယ် files = os.listdir(".") print(f"Files: {files}") # Folder ဆောက်မယ် if not os.path.exists("test_folder"): os.mkdir("test_folder") print("Folder ဆောက်ပြီး") # File ရှိ/မရှိ စစ်မယ် if os.path.exists("test.txt"): print("File ရှိတယ်") else: print("File မရှိဘူး")

Using pathlib (Modern Way):

pathlib_basic.py
from pathlib import Path # လက်ရှိ directory current = Path(".") print(f"Current: {current.absolute()}") # Directory ထဲက .py file တွေ ရှာမယ် for py_file in current.glob("*.py"): print(f"Python file: {py_file.name}") # Folder ဆောက်မယ် new_folder = Path("my_folder") new_folder.mkdir(exist_ok=True) # ရှိပြီးသားဆို error မတက် # File ရှိ/မရှိ စစ်မယ် test_file = Path("test.txt") if test_file.exists(): print("File ရှိတယ်") else: print("File မရှိဘူး")

Checking File vs Directory:

check_file_type.py
from pathlib import Path path = Path("test.txt") if path.exists(): if path.is_file(): print(f"{path} က file") elif path.is_dir(): print(f"{path} က directory") else: print(f"{path} မရှိဘူး")

Getting File Metadata:

file_metadata.py
from pathlib import Path import os from datetime import datetime file_path = Path("test.txt") if file_path.exists(): # File size size = file_path.stat().st_size print(f"Size: {size} bytes") # Creation time created = datetime.fromtimestamp(file_path.stat().st_ctime) print(f"Created: {created}") # Modification time modified = datetime.fromtimestamp(file_path.stat().st_mtime) print(f"Modified: {modified}") # File extension print(f"Extension: {file_path.suffix}") # File name without extension print(f"Name: {file_path.stem}")

Walking Directory Trees:

walk_directories.py
from pathlib import Path # Method 1: pathlib (Modern) root = Path(".") print("All Python files:") for py_file in root.rglob("*.py"): # Recursive print(f" {py_file}") # Method 2: os.walk (Traditional) import os print("\nDirectory tree:") for dirpath, dirnames, filenames in os.walk("."): print(f"Directory: {dirpath}") for filename in filenames: print(f" File: {filename}")

Creating Nested Directories:

nested_directories.py
from pathlib import Path # Single directory Path("folder1").mkdir(exist_ok=True) # Nested directories - parents=True က parent folder တွေ အလိုလို ဆောက်ပေးတယ် nested = Path("folder1/folder2/folder3") nested.mkdir(parents=True, exist_ok=True) print("Nested folders ဆောက်ပြီး")

Safe File Deletion:

safe_deletion.py
from pathlib import Path def safe_delete_file(filepath): """File ကို သေချာစစ်ပြီး ဖျက်မယ်""" path = Path(filepath) if not path.exists(): print(f"{filepath} မရှိဘူး") return if path.is_file(): path.unlink() # File ဖျက်မယ် print(f"{filepath} ဖျက်ပြီး") else: print(f"{filepath} က file မဟုတ်ဘူး") # Example safe_delete_file("test.txt")

Using shutil (Heavy Operations):

shutil_operations.py
import shutil from pathlib import Path # File copy shutil.copy("source.txt", "destination.txt") # File move shutil.move("old_location.txt", "new_location.txt") # Copy entire directory tree shutil.copytree("source_folder", "destination_folder") # Delete entire directory tree (DANGEROUS!) if Path("temp_folder").exists(): shutil.rmtree("temp_folder") print("Folder အကုန် ဖျက်ပြီး")

Error Handling for File Operations

File operations တွေမှာ error တက်တာ အဖြစ်များတယ်။ သူတို့ကို ကောင်းကောင်း handle လုပ်ရမယ်။

FileNotFoundError:

handle_file_not_found.py
try: with open("missing.txt", "r") as f: content = f.read() except FileNotFoundError: print("Error: File မရှိဘူး") # Alternative action with open("missing.txt", "w") as f: f.write("Default content") print("File အသစ် ဆောက်ပြီး default content ထည့်ပြီ")

PermissionError:

handle_permission_error.py
try: with open("readonly.txt", "w") as f: f.write("Trying to write") except PermissionError: print("Error: File ကို ရေးခွင့် မရှိဘူး") print("File က read-only ဖြစ်နေနိုင်တယ်")

Checking Before Operations:

check_before_operation.py
from pathlib import Path filename = "data.txt" filepath = Path(filename) # Check before reading if filepath.exists() and filepath.is_file(): with open(filepath, "r") as f: content = f.read() print(content) else: print(f"{filename} မရှိဘူး မဟုတ်လည်း file မဖြစ်နိုင်ဘူး") # Check before writing (prevent overwrite) if filepath.exists(): response = input(f"{filename} ရှိပြီးသား။ Overwrite လုပ်မလား? (y/n): ") if response.lower() != 'y': print("Operation cancelled") else: with open(filepath, "w") as f: f.write("New content")

Comprehensive Error Handling:

comprehensive_error_handling.py
def safe_read_file(filename): """File ကို safely ဖတ်မယ်""" try: with open(filename, "r", encoding="utf-8") as f: return f.read() except FileNotFoundError: print(f"Error: {filename} ကို ရှာမတွေ့ဘူး") return None except PermissionError: print(f"Error: {filename} ကို ဖတ်ခွင့် မရှိဘူး") return None except UnicodeDecodeError: print(f"Error: {filename} က UTF-8 မဟုတ်ဘူး") return None except Exception as e: print(f"Unexpected error: {e}") return None # Usage content = safe_read_file("data.txt") if content: print("File content:") print(content) else: print("File ဖတ်လို့ မရဘူး")

အနှစ်ချုပ်

bro... File I/O အကြောင်း သိသင့်တာ အကုန် ပြောပြပြီးပြီ။

Key Concepts:

  • File Modes: r (read), w (write), a (append), x (exclusive), b (binary)
  • Context Manager: အမြဲ with open() as f: သုံးသင့်
  • Encoding: Text file တွေမှာ encoding="utf-8" ထည့်ဖို့မမေ့ နဲ့
  • Binary Files: rb, wb သုံး၊ encoding မထည့်နဲ့
  • CSV: csv.reader(), csv.DictWriter() သုံး
  • JSON: json.dump(), json.load() သုံး
  • File System: pathlib က modern ပေါ့
  • Error Handling: FileNotFoundError, PermissionError တွေကို handle လုပ်

Suggestion:

  • အမြဲ with statement သုံးသင့် (auto close)
  • Text file တွေမှာ encoding="utf-8" ထည့်
  • Large file တွေ ဖတ်ရင် iterate လုပ်ပါ (memory efficient)
  • Error handling ကို မမေ့နဲ့
  • File operation တွေ မလုပ်ခင် existence check လုပ်ပါ
  • Binary mode နဲ့ encoding parameter ကို တွဲသုံးလို့ မရဘူးနော်
  • pathlib က os ထက် ပိုကောင်းတယ်
File I/O Skill! Real-world programming မှာ file တွေ နဲ့ မကြာမကြာအလုပ်လုပ်ရမှာ။ ဒီ chapter မှာ ပြောထားတဲ့ အကြောင်းတွေက bro ရဲ့ program တွေကို persistent data သိမ်းဖို့၊ config file တွေ ဖတ်ဖို့၊ log တွေ ရေးဖို့ အသုံးဝင်မှာ။

Quick Reference

file_io_cheatsheet.py
# === Text File Operations === with open("file.txt", "r", encoding="utf-8") as f: content = f.read() # Read all lines = f.readlines() # Read as list for line in f: # Iterate with open("file.txt", "w", encoding="utf-8") as f: f.write("text") # Write string f.writelines(lines) # Write list # === Binary File Operations === with open("file.jpg", "rb") as f: data = f.read() with open("file.jpg", "wb") as f: f.write(data) # === CSV Operations === import csv with open("data.csv", "r") as f: reader = csv.reader(f) dict_reader = csv.DictReader(f) with open("data.csv", "w", newline="") as f: writer = csv.writer(f) dict_writer = csv.DictWriter(f, fieldnames=[...]) # === JSON Operations === import json json.dumps(obj) # Object → String json.loads(string) # String → Object json.dump(obj, file) # Object → File json.load(file) # File → Object # === Path Operations === from pathlib import Path p = Path("file.txt") p.exists() # Check existence p.is_file() # Check if file p.is_dir() # Check if directory p.mkdir(exist_ok=True) # Create directory p.unlink() # Delete file p.glob("*.py") # Find files # === File System Operations === import shutil shutil.copy(src, dst) # Copy file shutil.move(src, dst) # Move file shutil.copytree(src, dst) # Copy directory shutil.rmtree(path) # Delete directory