Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Python Read Files

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

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

  • read(), readline(), readlines() တစ်ခုချင်းက ဘာ type ပြန်ပေးလဲ၊ \n ပါလား ခန့်မှန်းနိုင်ဖို့
  • File ကို for loop နဲ့ stream လုပ်ပြီး file အကြီးကြီးတွေကို memory နည်းနည်းနဲ့ ဖတ်နိုင်ဖို့
  • File position ကြောင့် ဒုတိယ read() က "" ပြန်တာကို ရှင်းပြနိုင်ဖို့
  • CSV file တွေကို split(",") အစား csv module နဲ့ ဖတ်နိုင်ဖို့

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

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

File တစ်ခုကို ဖတ်တာ ရုပ်ရှင်ကြည့်တာနဲ့ တူပါတယ်။ Player မှာ "ဘယ်နေရာ ရောက်နေပြီလဲ" ဆိုတဲ့ မှတ်တိုင် (position) ရှိပါတယ်။ read() က အဆုံးထိ တစ်ခါတည်း ကြည့်ပစ်တာ၊ readline() က ဇာတ်ကွက် တစ်ခန်းပဲ ကြည့်တာ၊ for loop ကတော့ တစ်ခန်းပြီး တစ်ခန်း ဆက်ကြည့်တာပါ။

အဆုံးထိ ရောက်ပြီးရင် ထပ်ကြည့်လို့ ဘာမှ မကျန်တော့ပါဘူး — read() ကို ထပ်ခေါ်ရင် string အလွတ် "" ရပါတယ်။ File ကြီးတွေအတွက် တစ်ခန်းချင်း ကြည့်တဲ့ နည်းက အကောင်းဆုံးပါ၊ ဇာတ်ကား တစ်ကားလုံးကို ခေါင်းထဲ တစ်ပြိုင်တည်း ထည့်ထားစရာ မလိုလို့ပါ။

Problem → Why → Solution

ပြဿနာ: log file ကြီးကြောင့် server က memory ကုန်တာ

Developer တစ်ယောက်က ERROR line တွေကို ရေတွက်ဖို့ ဒီ script ကို ရေးပါတယ်။ Test file (100 KB) နဲ့ စမ်းတော့ အဆင်ပြေပါတယ်။ Production server ပေါ်က 6 GB log file နဲ့ run တော့ process က memory အားလုံး သုံးပြီး ရပ်သွားပါတယ်။ ဒါ့အပြင် ပထမ ERROR line ကို print ထုတ်ချင်လို့ read() ကို နောက်တစ်ခါ ခေါ်တော့ ဘာမှ မထွက်ပါဘူး။

count_errors.py
with open("app.log", encoding="utf-8") as f:
    text = f.read()                     # the whole 6 GB file as one string
    errors = text.split("\n")           # ...and a second copy as a list
    print(sum("ERROR" in line for line in errors))

    again = f.read()                    # returns "" - the position is at the end
    print(again[:80])

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

read() က file တစ်ခုလုံးကို string တစ်ခုအဖြစ် memory ထဲ တင်ပြီး split() က list အဖြစ် နောက်ထပ် copy တစ်ခု ထပ်လုပ်ပါတယ်။ File ကြီးလာတာနဲ့အမျှ memory လည်း တိုက်ရိုက် ကြီးလာပါတယ်။ ဒုတိယ read() က "" ပြန်တာကတော့ file object မှာ position ရှိလို့ပါ — ပထမ read() က အဆုံးကို ရွှေ့ထားပြီးသားမို့ ဖတ်စရာ မကျန်တော့ပါဘူး။

Core concept: ဖတ်နည်း လေးမျိုးနဲ့ file position

Text mode နဲ့ ဖွင့်ထားတဲ့ file object မှာ ဖတ်နည်း လေးမျိုး ရှိပြီး အားလုံးက လက်ရှိ position ကနေ စဖတ်ပြီး ဖတ်ပြီးသလောက် position ကို ရှေ့တိုးပါတယ်။ ဘယ်နည်းကို ရွေးမလဲဆိုတာ file အရွယ်အစားနဲ့ data ကို ဘယ်လို သုံးမလဲ ပေါ် မူတည်ပါတယ်။

နည်းပြန်ပေးတာသုံးသင့်တဲ့အချိန်
f.read()ကျန်တဲ့ content အကုန် str တစ်ခုFile သေးပြီး တစ်ခါတည်း လိုတဲ့အခါ
f.readline()Line တစ်ကြောင်း (\n ပါ)၊ အဆုံးမှာ ""Header line တစ်ကြောင်းပဲ လိုတဲ့အခါ
f.readlines()Line တွေရဲ့ list (\n ပါ)Line အားလုံး list အဖြစ် လိုပြီး file သေးတဲ့အခါ
for line in f:Line တစ်ကြောင်းချင်းFile ကြီးတွေ၊ ပုံမှန် အခြေအနေ အများစု

for line in f: က memory ထဲမှာ line တစ်ကြောင်း (buffer အသေးလေးနဲ့အတူ) ပဲ ထားလို့ file 6 GB ဖြစ်ဖြစ် 6 KB ဖြစ်ဖြစ် memory သုံးစွဲမှု အတူတူလောက်ပဲ ရှိပါတယ်။ Line တိုင်းရဲ့ အဆုံးမှာ \n ပါလာပါတယ် (file ရဲ့ နောက်ဆုံး line မှာ newline မရှိရင်တော့ မပါပါဘူး)။ ဒါကြောင့် နှိုင်းယှဉ်တာ၊ print ထုတ်တာ မလုပ်ခင် line.rstrip("\n") ဒါမှမဟုတ် line.strip() နဲ့ ဖယ်ပါ။

အဆုံးကို ရောက်ပြီးသားဆိုတာကို string အလွတ်နဲ့ သိရပါတယ်။ readline() က "" ပြန်ရင် file ပြီးပါပြီ၊ "\n" ပြန်ရင်တော့ blank line တစ်ကြောင်းပဲ ဖြစ်ပြီး ဆက်ဖတ်စရာ ရှိပါသေးတယ်။ File ကို အစကနေ ပြန်ဖတ်ချင်ရင် f.seek(0) နဲ့ position ကို အစ ပြန်ရွှေ့ပါ ဒါမှမဟုတ် file ကို အသစ် ပြန်ဖွင့်ပါ။ Binary file အကြီးတွေအတွက်တော့ f.read(65536) လို size ပေးပြီး chunk လိုက် ဖတ်ပါ၊ "" ပြန်လာတဲ့အထိ loop ပတ်ပါ။

Text mode မှာ ဖတ်တာက byte တွေကို စာသားအဖြစ် decode လုပ်တာလည်း ပါလို့ အဲဒီအဆင့်မှာ fail ဖြစ်နိုင်ပါတယ်။ File ထဲက byte တစ်ခုက UTF-8 မမှန်ရင် ကျန်တဲ့ အပိုင်းတွေ အကုန် မှန်နေရင်တောင် အဲဒီနေရာမှာ UnicodeDecodeError ဖြစ်ပါတယ်။ Log အဟောင်းတွေကို ရှာဖွေတာလို ဖတ်လို့ရတဲ့ အပိုင်းပဲ လိုတဲ့အခါ errors="replace" နဲ့ ဖွင့်ပါ၊ decode မရတဲ့ byte တိုင်းက program ကို မရပ်ဘဲ U+FFFD replacement character ဖြစ်သွားပါတယ်။ တိတိကျကျ သိမ်းရမယ့် data အတွက်တော့ မသုံးပါနဲ့၊ content ကို တိတ်တိတ်လေး ပြောင်းပစ်လို့ပါ။

မှတ်ထားရမယ့် ပုံစံ
  1. open() က cursor ကို အစမှာ ထား
  2. ဖတ်တိုင်း cursor ရှေ့တိုး
  3. အဆုံးရောက်ရင် "" ပြန်ရ
  4. seek(0) မှ အစ ပြန်ရောက်

ဖတ်နည်း မတူတာက cursor ကို တစ်ကြိမ်မှာ ဘယ်လောက် ရွှေ့မလဲ ဆိုတာပဲ ကွာတာပါ။

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

python
with open(path, encoding="utf-8") as f:
    for line in f:                  # streams: one line in memory at a time
        process(line.rstrip("\n"))

with open(path, encoding="utf-8") as f:
    header = f.readline()           # just the first line
    rest = f.read()                 # everything after it

text = path.read_text(encoding="utf-8")   # small files only

ပုံမှန် အသုံးများဆုံးက for line in f: ပါ၊ line တိုင်းကနေ \n ကို ဖယ်ပါ။ readline() နဲ့ read() ကို ဆက်တိုက် ခေါ်ရင် ဒုတိယ call က ပထမ call ရပ်ခဲ့တဲ့ နေရာကနေ ဆက်ဖတ်ပါတယ်။ path.read_text() က file သေးသေးလေးတွေအတွက် shortcut ပါ။

Example: ဖတ်နည်း သုံးမျိုးကို နှိုင်းယှဉ်ခြင်း

ဒီ example က temporary folder ထဲမှာ line သုံးကြောင်းပါတဲ့ file တစ်ခု ဖန်တီးပြီး နည်းသုံးမျိုးနဲ့ ဖတ်ပါတယ်။ repr() က \n ကို မြင်ရအောင် ပြပေးလို့ ဘယ်နည်းက newline ကို ထိန်းထားလဲ တိတိကျကျ မြင်ရပါတယ်။

read_ways.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "readme.txt"
    path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")

    with open(path, encoding="utf-8") as f:
        content = f.read()              # the whole file as one string
    print(repr(content))

    with open(path, encoding="utf-8") as f:
        first = f.readline()            # one line, newline included
        rest = f.readlines()            # every remaining line, as a list
    print(repr(first))
    print(rest)

    with open(path, encoding="utf-8") as f:
        for number, line in enumerate(f, start=1):   # one line at a time
            print(number, line.rstrip("\n"))

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

  1. Line 6path.write_text("First line.\nSecond line.\nThird line.\n", encoding="utf-8")

    ဖတ်စရာ file ကို ဖန်တီးတာပါ။ Windows မှာ text mode က \n ကို disk ပေါ်မှာ \r\n အဖြစ် ရေးပေမယ့် text mode နဲ့ ပြန်ဖတ်တဲ့အခါ \n အဖြစ် ပြန်ပြောင်းပေးလို့ output က system တိုင်းမှာ အတူတူပါပဲ။

  2. Line 9content = f.read() # the whole file as one string

    read() က str တစ်ခုတည်း ပြန်ပေးပြီး \n သုံးခုလုံး အထဲမှာ ပါပါတယ်။ repr() ကြောင့် output မှာ quote နဲ့ \n ကို မြင်ရပါတယ်။

  3. Lines 13-14rest = f.readlines() # every remaining line, as a list

    readline() က ပထမ line ကို ဖတ်ပြီး cursor ကို ဒုတိယ line အစမှာ ထားခဲ့လို့ readlines() က ကျန်တဲ့ line နှစ်ကြောင်းကိုပဲ ရပါတယ်။ "First line." က list ထဲမှာ မပါတာ သတိထားကြည့်ပါ။

  4. Lines 19-20for number, line in enumerate(f, start=1): # one line at a time

    File object ကိုယ်တိုင်က iterator ဖြစ်လို့ for loop က line တစ်ကြောင်းချင်း ယူပါတယ်။ enumerate(..., start=1) က line နံပါတ်ကို 1 ကစပြီး ပေးပါတယ်။ rstrip("\n") မပါရင် print() ရဲ့ newline နဲ့ ပေါင်းပြီး line ကြား blank line ပေါ်ပါမယ်။

You should see
'First line.\nSecond line.\nThird line.\n'
'First line.\n'
['Second line.\n', 'Third line.\n']
1 First line.
2 Second line.
3 Third line.

CSV ကို csv module နဲ့ ဖတ်ပါ

line.split(",") က "Smith, John" လို quote ထဲမှာ comma ပါတဲ့ value တွေကို နှစ်ပိုင်း ခွဲပစ်ပါတယ်။ csv module က quoting စည်းကမ်းတွေကို နားလည်ပါတယ်။ csv documentation အတိုင်း file ကို newline="" နဲ့ ဖွင့်ပါ၊ quote ထဲမှာ ပါတဲ့ newline တွေကို csv module ကိုယ်တိုင် ကိုင်တွယ်နိုင်ဖို့ပါ။ DictReader က ပထမ line ကို column name အဖြစ် ယူပြီး row တိုင်းကို dict အဖြစ် ပေးပါတယ်။

read_csv.py
import csv
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "people.csv"
    path.write_text('name,city\nAye,Yangon\n"Smith, John",Mandalay\n', encoding="utf-8")

    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            print(row["name"], "|", row["city"])

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

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

Ops team တွေ နေ့စဉ် ရေးတဲ့ script တွေက log file ကို stream လုပ်ပြီး ERROR line တွေ ရေတွက်တာ၊ IP address တစ်ခုချင်းရဲ့ request အရေအတွက် စုတာ၊ နှေးတဲ့ request တွေ စစ်ထုတ်တာ လုပ်ကြပါတယ်။ for line in f: နဲ့ collections.Counter ကို တွဲသုံးရင် gigabyte ချီတဲ့ file တွေကိုတောင် memory အနည်းငယ်နဲ့ တစ်ကြိမ်တည်း ဖြတ်ဖတ်ပြီး summary ထုတ်နိုင်ပါတယ်။

Data import လုပ်တဲ့ feature တွေမှာတော့ user upload လုပ်လိုက်တဲ့ CSV ကို csv.DictReader နဲ့ ဖတ်ပြီး row တိုင်းကို untrusted input အဖြစ် သဘောထားပါတယ် — column ပျောက်နေတာ၊ number နေရာမှာ စာသား ပါလာတာ၊ encoding မှားတာတွေကို စစ်ပြီး row နံပါတ်နဲ့တကွ error message ပြန်ပေးပါတယ်။ File ဖတ်တာက မှန်ကန်တဲ့ data ရဖို့ အစပဲ ဖြစ်ပါတယ်၊ validation က တကယ့် အလုပ်ပါ။

Config file တွေကိုလည်း ဒီနည်းနဲ့ပဲ ဖတ်ပါတယ်။ JSON settings ကို json.load(f) ဆီ ဖွင့်ထားတဲ့ file object ကို တိုက်ရိုက် ပေးပြီး TOML ဆိုရင် Python 3.11 ကစပြီး ပါလာတဲ့ tomllib ကို "rb" mode နဲ့ ဖွင့်ထားတဲ့ file နဲ့ သုံးပါတယ်။ Parser က file ကို ကိုယ်တိုင် ဖတ်လို့ ကိုယ်က line တွေ ခွဲစရာ မလိုပါဘူး။

အမှားများ

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

1. \n ကို မဖယ်ဘဲ နှိုင်းယှဉ်တာ

users.txt ထဲမှာ admin ပါနေရက်နဲ့ if line == "admin": က ဘယ်တော့မှ True မဖြစ်ပါဘူး၊ line က တကယ်တော့ "admin\n" ဖြစ်နေလို့ပါ။ line.strip() == "admin" လို့ ရေးပါ။

2. File တစ်ခုတည်းကို နှစ်ကြိမ် loop ပတ်တာ

ပထမ for loop က cursor ကို အဆုံးထိ ရွှေ့ပြီးသားမို့ ဒုတိယ loop က တစ်ကြိမ်မှ မပတ်ဘဲ ပြီးသွားပါတယ်၊ error လည်း မပြပါဘူး။ Line တွေကို နှစ်ကြိမ် လိုရင် f.seek(0) ခေါ်ပါ ဒါမှမဟုတ် file သေးရင် list တစ်ခုထဲ သိမ်းထားပါ။

3. File ကြီးကို read() ဒါမှမဟုတ် readlines() နဲ့ ဖတ်တာ

File အရွယ်အစား မသိရင် read() နဲ့ readlines() နှစ်ခုလုံးက file တစ်ခုလုံးကို memory ထဲ တင်ပါတယ်။ Log နဲ့ export လို ကြီးလာနိုင်တဲ့ file တွေကို for line in f: နဲ့ပဲ ဖတ်ပါ။

Best Practices

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

  • File အရွယ်အစားကို ကိုယ်မထိန်းချုပ်နိုင်ရင် for line in f: ကို default အဖြစ် ရွေးပါ။
  • CSV, JSON, TOML လို format တွေကို ကိုယ်တိုင် parse မလုပ်ဘဲ standard library module တွေကို သုံးပါ။
  • File ထဲက data ကို untrusted input အဖြစ် သဘောထားပြီး type နဲ့ range ကို စစ်ပါ။
  • Error message တွေမှာ line နံပါတ်ကို ထည့်ပါ၊ enumerate(f, start=1) က ဒါကို လွယ်ကူစေပါတယ်။

Mini challenge

Mini challenge: log file ကို summary ထုတ်ပါ

"LEVEL message" ပုံစံ line တွေပါတဲ့ log file ကို တစ်ကြိမ်တည်း stream လုပ်ပြီး level တစ်ခုချင်းရဲ့ အရေအတွက်ကို ရေတွက်ကာ ERROR message တွေကို စုတဲ့ summarize_log() ကို ရေးပါ။

  • File ကို for line in f: နဲ့ ဖတ်ရမယ်၊ read() ဒါမှမဟုတ် readlines() မသုံးရ
  • Blank line တွေကို ကျော်ရမယ်
  • Level အရေအတွက်ကို collections.Counter နဲ့ ရေတွက်ရမယ်
  • Log file ကို temporary directory ထဲမှာ ဖန်တီးရမယ်
log_summary.py
import tempfile
from collections import Counter
from pathlib import Path

SAMPLE = (
    "INFO server started\n"
    "WARNING disk 85% full\n"
    "ERROR payment timeout order=17\n"
    "\n"
    "INFO request /home\n"
    "ERROR payment timeout order=21\n"
)


def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
    """Stream the log once: count lines per level and collect ERROR messages."""
    # TODO: open the file with utf-8 and loop over it line by line
    # TODO: strip each line, skip blank ones, split off the level
    # TODO: count the level; keep the message when the level is ERROR
    ...


# TODO: write SAMPLE to app.log in a temporary directory, summarize it, print results

ရလဒ်: Program က ဒီလို print ထုတ်ရပါမယ်: {'INFO': 2, 'WARNING': 1, 'ERROR': 2} ERROR: payment timeout order=17 ERROR: payment timeout order=21

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

line.partition(" ") က ပထမ space မှာ နှစ်ပိုင်း ခွဲပြီး (level, " ", message) tuple ပြန်ပေးပါတယ်။ Counter မှာ မရှိသေးတဲ့ key ကို counts[key] += 1 လုပ်လို့ ရပါတယ်။

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

SAMPLE = (
    "INFO server started\n"
    "WARNING disk 85% full\n"
    "ERROR payment timeout order=17\n"
    "\n"
    "INFO request /home\n"
    "ERROR payment timeout order=21\n"
)


def summarize_log(path: Path) -> tuple[Counter[str], list[str]]:
    """Return a level -> count Counter and the list of ERROR messages."""
    levels: Counter[str] = Counter()
    errors: list[str] = []
    with open(path, encoding="utf-8") as f:
        for raw_line in f:
            line = raw_line.strip()
            if not line:
                continue                      # blank line
            level, _, message = line.partition(" ")
            levels[level] += 1
            if level == "ERROR":
                errors.append(message)
    return levels, errors


with tempfile.TemporaryDirectory() as tmp:
    log_path = Path(tmp) / "app.log"
    log_path.write_text(SAMPLE, encoding="utf-8")
    levels, errors = summarize_log(log_path)
    print(dict(levels))
    for message in errors:
        print("ERROR:", message)

Quick Quiz 1 / 3

File ထဲမှာ "a\nb\n" ရှိပါတယ်။ f.readline() ကို သုံးကြိမ် ဆက်တိုက် ခေါ်ရင် ဘာတွေ ပြန်ရမလဲ။

Quick Quiz 2 / 3

File object တစ်ခုတည်းပေါ်မှာ data = f.read() ကို ခေါ်ပြီးနောက် ချက်ချင်း lines = f.readlines() ကို ခေါ်ပါတယ်။ lines က ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

10 GB ရှိတဲ့ log ထဲက "timeout" ပါတဲ့ line တွေကို ရေတွက်ဖို့ ဘယ်နည်းက အကောင်းဆုံးလဲ။

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

  • read() က str တစ်ခု၊ readline() က line တစ်ကြောင်း၊ readlines() က list၊ for line in f: က line တစ်ကြောင်းချင်း ပေးပါတယ်။
  • ဖတ်တိုင်း cursor ရှေ့တိုးပြီး အဆုံးမှာ "" ရပါတယ်၊ ပြန်ဖတ်ချင်ရင် f.seek(0) ခေါ်ပါ။
  • Line တိုင်းမှာ \n ပါလို့ နှိုင်းယှဉ်ခင် strip() လုပ်ပါ။
  • File ကြီးတွေကို for line in f: နဲ့ stream လုပ်ပြီး CSV ကို csv module နဲ့ ဖတ်ပါ။

Python Documentation — Reading and Writing Files — Python Software Foundation

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

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

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

Python Read Files | Thuta Learning