Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Python Write/Create Files

Pythonသင်ခန်းစာ 3225 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • "w", "a", "x" mode တွေထဲက အလုပ်တစ်ခုအတွက် မှန်ကန်တဲ့ mode ကို ရွေးနိုင်ဖို့
  • write() က newline မထည့်ကြောင်းနဲ့ ရေးခဲ့တဲ့ character အရေအတွက်ကို return ပြန်ကြောင်း ရှင်းပြနိုင်ဖို့
  • print(..., file=f) နဲ့ writelines() ကို သုံးပြီး line အများကြီး ရေးနိုင်ဖို့
  • Temp file + os.replace() နဲ့ crash ဖြစ်လည်း file တစ်ဝက်တစ်ပျက် မကျန်အောင် သိမ်းနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

File ထဲ ရေးတာကို whiteboard ပေါ် ရေးတာနဲ့ နှိုင်းကြည့်ပါ။ "w" က board ကို အရင် ဖျက်ပြီးမှ ရေးတာပါ၊ အရင်ရှိတာ အကုန် ပျောက်ပါတယ်။ "a" က ရှိပြီးသား စာတွေ အောက်မှာ ဆက်ရေးတာပါ။ "x" ကတော့ "board အလွတ် ဖြစ်မှပဲ ရေးမယ်၊ တစ်ယောက်ယောက် ရေးထားပြီးသားဆိုရင် မထိဘူး" ဆိုတဲ့ သတိကြီးတဲ့ နည်းပါ။

သတိထားရမယ့် အချက်တစ်ခုက write() က စာကြောင်းအသစ် (newline) ကို အလိုအလျောက် မထည့်ပေးတာပါ။ print() လို မဟုတ်ပါဘူး။ \n ကို ကိုယ်တိုင် ထည့်မပေးရင် စာကြောင်းတွေ အားလုံး line တစ်ကြောင်းထဲမှာ ကပ်လျက် ဖြစ်သွားပါမယ်။

Problem → Why → Solution

ပြဿနာ: order ဆယ်ခု ရေးလိုက်တာ တစ်ခုပဲ ကျန်တယ်

အောက်က script က order တစ်ခုချင်းကို orders.txt ထဲ ရေးဖို့ ရည်ရွယ်ပါတယ်။ Run ပြီး file ကို ဖွင့်ကြည့်တော့ နောက်ဆုံး order တစ်ခုပဲ ရှိပါတယ်၊ error လည်း တစ်ခုမှ မပေါ်ခဲ့ပါဘူး။ မနေ့က report အဟောင်းလည်း ပျောက်သွားပါပြီ။ Settings file ကို သိမ်းနေတုန်း laptop battery ကုန်သွားရင်တော့ file က တစ်ဝက်ပဲ ရေးထားတဲ့ အခြေအနေ ဒါမှမဟုတ် အလွတ် ဖြစ်နေနိုင်ပါတယ်။

save_orders.py
orders = ["#101 tea", "#102 coffee", "#103 juice"]

for order in orders:
    with open("orders.txt", "w", encoding="utf-8") as f:   # reopened every pass
        f.write(order)                                      # and no newline

# orders.txt now contains only: #103 juice

ဘာကြောင့် ဒီလို ဖြစ်ရတာလဲ

"w" mode က file ကို ဖွင့်လိုက်တဲ့ အချိန်မှာတင် truncate လုပ်ပါတယ်။ Loop ထဲမှာ ဖွင့်ထားလို့ iteration တိုင်းမှာ ယခင် order ကို ဖျက်ပြီး အသစ် ရေးပါတယ်။ ဖြေရှင်းနည်းက file ကို loop အပြင်မှာ တစ်ကြိမ်ပဲ ဖွင့်တာ ဒါမှမဟုတ် "a" mode သုံးတာပါ။ Write လုပ်တာက instant မဟုတ်ဘဲ buffer ကနေ disk ဆီ အဆင့်ဆင့် ရောက်တာမို့ အလယ်မှာ ပြတ်သွားရင် file တစ်ဝက် ကျန်နိုင်ပါတယ်။

Core concept: mode က ရှိပြီးသား data ရဲ့ ကံကြမ္မာကို ဆုံးဖြတ်တယ်

ရေးဖို့ mode သုံးမျိုးကြားက ကွာခြားချက်က file ရှိပြီးသား ဖြစ်နေတဲ့အခါ ဘာလုပ်လဲ ဆိုတာပဲ ဖြစ်ပါတယ်။ File မရှိရင်တော့ သုံးမျိုးလုံး အသစ် ဖန်တီးပါတယ် (parent folder ရှိရမယ်၊ မရှိရင် FileNotFoundError ရပါတယ်)။

ModeFile ရှိပြီးသားဆိုရင်သုံးသင့်တဲ့ နေရာ
"w"အလွတ်လုပ်ပြီး အစကနေ ရေးReport ကို အသစ်ကနေ ပြန်ထုတ်တာ
"a"ရှိပြီးသား content ကို ထိန်းပြီး အဆုံးမှာ ဆက်ရေးLog နဲ့ audit trail
"x"FileExistsError raise လုပ်ပြီး ဘာမှ မပြောင်းမတော်တဆ overwrite မဖြစ်စေချင်တဲ့ file

Text mode မှာ f.write(text) က str ကိုပဲ လက်ခံပြီး ရေးလိုက်တဲ့ character အရေအတွက်ကို return ပြန်ပါတယ်။ Number ရေးချင်ရင် str() ဒါမှမဟုတ် f-string နဲ့ ပြောင်းရပါမယ်၊ မဟုတ်ရင် TypeError ရပါတယ်။ print(value, file=f) ကတော့ str ပြောင်းတာရော newline ထည့်တာရော လုပ်ပေးလို့ line တစ်ကြောင်းချင်း ရေးဖို့ အဆင်ပြေပါတယ်။ f.writelines(list_of_strings) က list ထဲက string တွေကို ဆက်တိုက် ရေးပေမယ့် နာမည်က "lines" လို့ ဆိုထားရက်နဲ့ newline ကို မထည့်ပေးပါဘူး — "\n".join() နဲ့ write() ကို တွဲသုံးတာ ပိုရှင်းပါတယ်။

write() return ပြန်လာတာနဲ့ data က disk ပေါ် ရောက်ပြီလို့ မဆိုလိုပါဘူး။ Python က buffer ထဲမှာ စုထားပြီး buffer ပြည့်တဲ့အခါ၊ f.flush() ခေါ်တဲ့အခါ ဒါမှမဟုတ် file ပိတ်တဲ့အခါမှ operating system ဆီ ပို့ပါတယ်။ Operating system ကလည်း ခဏ cache လုပ်ထားနိုင်လို့ os.fsync(f.fileno()) က အဲဒါကို disk ပေါ် ရေးခိုင်းပါတယ်။ ဒါကြောင့် crash ဖြစ်ရင် ရလဒ် သုံးမျိုး ဖြစ်နိုင်ပါတယ် — file အဟောင်း၊ file အသစ် ဒါမှမဟုတ် နှစ်ခုကြား တစ်ဝက်တစ်ပျက်။ အရေးကြီးတဲ့ file တွေအတွက် deeper section က atomic write pattern က တတိယ ရလဒ်ကို ဖယ်ရှားပေးပါတယ်။

Text mode က newline တွေကိုလည်း ပြောင်းပေးပါတယ်။ Windows မှာ ကိုယ်ရေးလိုက်တဲ့ \n တိုင်းက disk ပေါ်မှာ \r\n ဖြစ်သွားပြီး Linux နဲ့ macOS မှာတော့ \n အတိုင်း ကျန်ပါတယ်။ Line ending ကို တိတိကျကျ ထိန်းချင်ရင် open(path, "w", encoding="utf-8", newline="\n") လို newline argument ပေးပါ၊ csv.writer နဲ့ ရေးတဲ့အခါကတော့ csv module က line ending ကို ကိုယ်တိုင် ရေးလို့ newline="" ပေးရပါမယ်။ Image လို binary data ကို "wb" နဲ့ ရေးပြီး write() ဆီ str အစား bytes ပေးရပါတယ်။

မှတ်ထားရမယ့် ပုံစံ
  1. File ရှိပြီးသားလား မေး
  2. ဖျက်ရမလား (w)
  3. ဆက်ရေးရမလား (a)
  4. ငြင်းရမလား (x)

Mode ကို ရွေးတာက ရှိပြီးသား data ရဲ့ ကံကြမ္မာကို ရွေးတာပါ၊ "w" ကိုတော့ ပြန်ပြင်လို့ မရပါဘူး။

အထွေထွေ ပုံစံ

python
with open(path, "w", encoding="utf-8") as f:   # or "a" / "x"
    f.write("text\n")                            # you add the newline
    print(value, file=f)                          # converts + adds newline
    f.write("\n".join(lines) + "\n")              # many lines at once

path.write_text(text, encoding="utf-8")          # small file, mode "w"

Mode ကို ရည်ရွယ်ချက်အလိုက် ရွေးပြီး encoding ကို အမြဲ ပေးပါ။ write() နဲ့ ရေးရင် \n ကို ကိုယ်တိုင် ထည့်ပါ၊ print(file=f) က ထည့်ပေးပါတယ်။ path.write_text() က "w" mode နဲ့ ဖွင့်၊ ရေး၊ ပိတ် ကို တစ်ခါတည်း လုပ်ပါတယ်။

Example: w, a, x ကို တစ်ဆက်တည်း

ဒီ example က temporary folder ထဲက log.txt ပေါ်မှာ mode သုံးမျိုးကို အစဉ်လိုက် သုံးပါတယ်။ "w" နဲ့ ဖန်တီး၊ "a" နဲ့ ဆက်ရေး၊ "x" နဲ့ overwrite လုပ်ဖို့ ကြိုးစားပြီး ငြင်းခံရတာကို မြင်ရပါမယ်။ နောက်ဆုံးမှာ file ကို ပြန်ဖတ်ပြီး ဘာတွေ ကျန်နေလဲ စစ်ပါတယ်။

write_modes.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    log = Path(tmp) / "log.txt"

    with open(log, "w", encoding="utf-8") as f:      # create, or empty an old file
        count = f.write("Log started.\n")
    print(f"write() returned {count}")

    with open(log, "a", encoding="utf-8") as f:      # keep content, add at the end
        f.write("New entry added.\n")
        print("Printed into the file", file=f)

    try:
        with open(log, "x", encoding="utf-8") as f:  # "x": create only if missing
            f.write("never written")
    except FileExistsError:
        print("x mode refused: log.txt already exists")

    print(log.read_text(encoding="utf-8"), end="")

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 8count = f.write("Log started.\n")

    "Log started." က character 12 လုံးဖြစ်ပြီး \n နဲ့ဆိုရင် 13 ဖြစ်လို့ write() က 13 ပြန်ပါတယ်။ Text mode မှာ ဒီ ဂဏန်းက byte အရေအတွက် မဟုတ်ဘဲ character အရေအတွက်ပါ။

  2. Lines 11-13print("Printed into the file", file=f)

    "a" mode က ပထမ line ကို ထိန်းထားပြီး အောက်မှာ ဆက်ရေးပါတယ်။ print(..., file=f) က screen အစား file ထဲ ရေးပြီး newline ကိုလည်း ထည့်ပေးပါတယ်။

  3. Lines 15-19except FileExistsError:

    log.txt ရှိပြီးသားမို့ open(log, "x") က file ကို မဖွင့်ခင်ကတည်းက FileExistsError raise လုပ်ပါတယ်။ "never written" က ဘယ်တော့မှ မရေးရပါဘူး၊ file content လည်း မပြောင်းပါဘူး။

  4. Line 21print(log.read_text(encoding="utf-8"), end="")

    File ကို ပြန်ဖတ်တော့ line သုံးကြောင်းလုံး ရှိနေပါတယ်။ File content ရဲ့ အဆုံးမှာ \n ရှိပြီးသားမို့ end="" နဲ့ print() ရဲ့ newline ကို ထပ်မထည့်ခိုင်းပါဘူး။

You should see
write() returned 13
x mode refused: log.txt already exists
Log started.
New entry added.
Printed into the file

Atomic write: တစ်ဝက်တစ်ပျက် file မကျန်စေနဲ့

Settings ဒါမှမဟုတ် save game လို file တွေကို "w" နဲ့ တိုက်ရိုက် ရေးရင် file ကို truncate လုပ်ပြီးနောက် ရေးမပြီးခင် crash ဖြစ်တာနဲ့ data အဟောင်းရော အသစ်ရော ပျောက်ပါတယ်။ ဘေးကင်းတဲ့ နည်းက:

1. Temp file ထဲ ရေး

Target နဲ့ folder တူတဲ့ temp file တစ်ခုထဲ content အပြည့်အစုံ ရေးပါ၊ folder တူမှ filesystem တူမှာပါ။

2. flush + fsync

f.flush() နဲ့ os.fsync() က data ကို disk ပေါ် တကယ် ရောက်အောင် လုပ်ပါတယ်။

3. os.replace()

os.replace(temp, target) က target ကို တစ်ဆင့်တည်းနဲ့ အစားထိုးပါတယ်။ Python documentation အရ POSIX system တွေမှာ အောင်မြင်ရင် ဒီ rename က atomic ဖြစ်လို့ reader တွေက file အဟောင်း ဒါမှမဟုတ် အသစ်ကိုပဲ မြင်ရပါတယ်။

atomic_save.py
import json
import os
import tempfile
from pathlib import Path


def save_json_atomic(path: Path, data: dict) -> None:
    tmp_path = path.with_name(path.name + ".tmp")
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)
        f.flush()
        os.fsync(f.fileno())          # ask the OS to commit the bytes to disk
    os.replace(tmp_path, path)        # swap the finished file into place


with tempfile.TemporaryDirectory() as tmp:
    settings = Path(tmp) / "settings.json"
    save_json_atomic(settings, {"theme": "dark", "font_size": 14})
    save_json_atomic(settings, {"theme": "light", "font_size": 16})
    print(json.loads(settings.read_text(encoding="utf-8")))

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Application log တွေ၊ audit trail တွေနဲ့ data export တွေက "a" mode ပေါ်မှာ အခြေခံပါတယ်။ Event တစ်ခု ဖြစ်တိုင်း line တစ်ကြောင်း ဆက်ရေးပြီး ယခင် record တွေကို ဘယ်တော့မှ မပြင်ပါဘူး။ Nightly report generator တွေကတော့ "w" နဲ့ report ကို အသစ်ကနေ ပြန်ထုတ်ပြီး invoice နံပါတ်လို file name တွေ ထပ်မနေစေချင်တဲ့ နေရာမှာ "x" နဲ့ ရှိပြီးသား file ကို မတော်တဆ ဖုံးမရေးမိအောင် ကာကွယ်ပါတယ်။

Text editor တွေ၊ package manager တွေနဲ့ database tool အများအပြားက atomic write pattern ကို သုံးကြပါတယ်။ Desktop app တစ်ခုရဲ့ settings.json ကို user က ပြင်နေတုန်း app crash ဖြစ်ရင်တောင် file အဟောင်း မပျက်ဘဲ ကျန်နေပါတယ်။ Web server တွေမှာ upload လုပ်လာတဲ့ file ကိုလည်း temp နာမည်နဲ့ အရင် သိမ်းပြီး စစ်ဆေးမှု အောင်မှ နာမည်အမှန်ကို ပြောင်းပါတယ်၊ ဒါမှ တခြား process တွေက ရေးနေဆဲ file ကို ဖတ်မိမှာ မဟုတ်ပါဘူး။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Loop ထဲမှာ "w" နဲ့ ဖွင့်တာ

Problem section ထဲကလို iteration တိုင်း "w" နဲ့ ပြန်ဖွင့်ရင် iteration တိုင်းက ယခင် content ကို ဖျက်ပါတယ်။ with block ကို loop အပြင်ကို ရွှေ့ပြီး loop ကို block ထဲမှာ ထားပါ။

2. writelines() က newline ထည့်ပေးမယ်လို့ ထင်တာ

f.writelines(["a", "b"]) က "ab" လို့ ရေးပါတယ်၊ line နှစ်ကြောင်း မဟုတ်ပါဘူး။ String တိုင်းမှာ \n ပါအောင် လုပ်ပါ ဒါမှမဟုတ် f.write("\n".join(items) + "\n") ကို သုံးပါ။

3. str မဟုတ်တာကို write() ဆီ ပို့တာ

f.write(42) က "write() argument must be str, not int" TypeError ပေးပါတယ်။ f.write(f"{42}\n") ဒါမှမဟုတ် print(42, file=f) ကို သုံးပါ။ Dict နဲ့ list တွေအတွက်တော့ str() မသုံးဘဲ json.dump() ကို သုံးပါ၊ ပြန်ဖတ်ရ လွယ်ပါတယ်။

4. မရှိသေးတဲ့ folder ထဲ ရေးတာ

"w" က file ကို ဖန်တီးပေးပေမယ့် folder ကို မဖန်တီးပေးပါဘူး၊ ဒါကြောင့် reports/2026/jan.txt ကို ရေးရင် reports/2026 မရှိသေးရင် FileNotFoundError ရပါတယ်။ မဖွင့်ခင် path.parent.mkdir(parents=True, exist_ok=True) ကို ခေါ်ပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • "w" ကို ရေးမယ့်အခါတိုင်း "ဒီ file အဟောင်း ပျောက်သွားရင် ရလား" လို့ ကိုယ့်ကိုယ်ကို မေးပါ။
  • File ကို loop မစခင် တစ်ကြိမ်ပဲ ဖွင့်ပြီး loop ထဲမှာ write() တွေ ခေါ်ပါ၊ မြန်လည်း မြန်ပါတယ်။
  • Structured data ကို str() နဲ့ မရေးဘဲ json ဒါမှမဟုတ် csv module နဲ့ ရေးပါ။
  • အရေးကြီးတဲ့ file တွေကို atomic write နဲ့ သိမ်းပြီး ပြန်ဖတ်ကြည့်ကာ စစ်ပါ။

Mini challenge

Mini challenge: audit log တစ်ခု တည်ဆောက်ပါ

Event တစ်ခုကို audit.log ထဲ line တစ်ကြောင်းအဖြစ် ဆက်ထည့်တဲ့ log_event() ကို ရေးပါ။ File အသစ်ဖြစ်မှပဲ "# audit log" header ကို ရေးရပြီး နောက်ပိုင်း call တွေမှာ header ထပ်မပါရပါ။

  • Header ကို "x" mode နဲ့ ရေးပြီး FileExistsError ကို ဖမ်းရမယ်
  • Event တွေကို "a" mode နဲ့ ဆက်ရေးရမယ်၊ "w" မသုံးရ
  • Event တစ်ခုချင်း line သီးခြားစီ ဖြစ်ရမယ်
  • Temporary directory ထဲမှာ စမ်းပြီး line အရေအတွက်ကို print ထုတ်ရမယ်
audit_log.py
import tempfile
from pathlib import Path


def log_event(path: Path, event: str) -> None:
    """Append one event; write the header only when the file is new."""
    # TODO: try to open the file in "x" mode and write "# audit log" plus a newline
    # TODO: if it already exists, skip the header
    # TODO: open in "a" mode and write the event on its own line
    ...


with tempfile.TemporaryDirectory() as tmp:
    audit = Path(tmp) / "audit.log"
    # TODO: log three events, then one more as if from a later run
    # TODO: print the file's content and the number of lines

ရလဒ်: Program က ဒီလို print ထုတ်ရပါမယ်: # audit log login aye export report logout aye login mya lines: 5

အရိပ်အမြွက် ကြည့်ရန်

try: with open(path, "x", ...) as f: ... except FileExistsError: pass ပုံစံကို သုံးပါ။ print(event, file=f) က newline ကို အလိုအလျောက် ထည့်ပေးပါတယ်။

အဖြေ ကြည့်ရန်
audit_log.py
import tempfile
from pathlib import Path


def log_event(path: Path, event: str) -> None:
    """Append an event line, creating the file with a header the first time."""
    try:
        with open(path, "x", encoding="utf-8") as f:
            f.write("# audit log\n")
    except FileExistsError:
        pass                                   # header is already there
    with open(path, "a", encoding="utf-8") as f:
        print(event, file=f)


with tempfile.TemporaryDirectory() as tmp:
    audit = Path(tmp) / "audit.log"
    for event in ["login aye", "export report", "logout aye"]:
        log_event(audit, event)
    log_event(audit, "login mya")              # a later run: no second header

    content = audit.read_text(encoding="utf-8")
    print(content, end="")
    print("lines:", len(content.splitlines()))

Quick Quiz 1 / 3

notes.txt မှာ "old\n" ရှိပါတယ်။ open("notes.txt", "a") နဲ့ f.write("new") ပြီးနောက် file content က ဘာလဲ။

Quick Quiz 2 / 3

Invoice file တစ်ခုကို ရှိပြီးသားဆိုရင် ဘယ်တော့မှ overwrite မဖြစ်စေချင်ပါဘူး။ ဘယ် mode ကို သုံးသင့်လဲ။

Quick Quiz 3 / 3

f.writelines(["a", "b", "c"]) ပြီးနောက် file ထဲမှာ line ဘယ်နှစ်ကြောင်း ရှိမလဲ။

မှတ်ထားရမယ့် အချက်များ

  • "w" က ဖွင့်တာနဲ့ truncate လုပ်၊ "a" က အဆုံးမှာ ဆက်ရေး၊ "x" က ရှိပြီးသား file ကို ငြင်းပါတယ်။
  • write() က str ကိုပဲ လက်ခံပြီး newline မထည့်ပါဘူး၊ print(file=f) က ထည့်ပေးပါတယ်။
  • writelines() ကလည်း newline မထည့်ပါဘူး၊ "\n".join() နဲ့ write() ကို ပိုသုံးပါ။
  • အရေးကြီးတဲ့ file တွေကို temp file + flush/fsync + os.replace() နဲ့ atomic ဖြစ်အောင် သိမ်းပါ။

Python Documentation — Reading and Writing Files — Python Software Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Python Write/Create Files | Thuta Learning