Python File Reading: File I/O මූලිකාංග - SC Guide

Python File Reading: File I/O මූලිකාංග - SC Guide

ආයුබෝවන් කට්ටිය! Python File Reading Essentials - SC Guide

මචංලා, කොහොමද ඔයාලට? අද අපි කතා කරන්න යන්නේ programming වලදී අත්‍යවශ්‍යම වෙන, හැමෝටම වැදගත් වෙන ටොපික් එකක් ගැන – ඒ තමයි File I/O, විශේෂයෙන්ම Python වලින් Files කියවන විදිය (Reading Files).

හිතලා බලන්නකෝ, ඔයාලා දවසට කොච්චර නම් files එක්ක වැඩ කරනවද කියලා? Word document එකක්, Excel sheet එකක්, නැත්නම් PDF එකක්. Computer එකත් එක්ක වැඩ කරනකොට මේ files කියන එක නැතුවම බැරි දෙයක්. Software එකක් හදනකොටත් අපිට Data Store කරන්න, Report generate කරන්න, Configuration load කරන්න වගේ දේවල් වලට files ඕන වෙනවා. ඉතින්, Python වගේ powerful language එකක files එක්ක වැඩ කරන විදිය හරියටම දැනගෙන ඉන්න එක ඔයාලට ලොකු වාසියක්.

අද අපි බලමු Python වලින් text files කියවන විදියට අදාළ මූලික කරුණු ටික, ඊට අමතරව practical tips කිහිපයකුත්, common errors විසඳගන්නෙ කොහොමද කියලත්. එහෙනම්, අපි පටන් ගමු නේද?

Python File Reading

ෆයිල් ඕපන් කරගමු - මුලින්ම පටන් ගමු! (Let's Open Files - Let's Start First!)

ඔයාලා පොතක් කියවනවා වගේම, computer එකේ තියෙන file එකක් කියවන්නත් කලින්, ඒක open කරගන්න ඕනේ. Python වලදී මේකට අපි `open()` function එක පාවිච්චි කරනවා. මේක හරිම සරලයි.

file_object = open("filename.txt", "mode")

මේකේ components දෙකක් තියෙනවා:

  • "filename.txt": ඔයාලට කියවන්න ඕනේ file එකේ නම (හෝ path එක).
  • "mode": File එක open කරන විදිය. මේකෙන් තමයි කියන්නේ අපි file එකෙන් කියවන්නද, ලියන්නද, append කරන්නද වගේ දේවල්.

File Opening Modes

Files කියවන්න (Read) භාවිතා කරන ප්‍රධාන modes කිහිපයක් මෙතන තියෙනවා. අපි අද වැඩිපුරම අවධානය යොමු කරන්නේ 'r' mode එකට.

  • 'r' (read): File එක කියවන්න විතරක් open කරනවා. මේක තමයි default mode එක. File එක නැත්නම් `FileNotFoundError` එකක් එනවා.
  • 'w' (write): File එකට ලියන්න open කරනවා. File එක තියෙනවා නම්, ඒකේ තියෙන හැමදෙයක්ම overwrite වෙනවා. File එක නැත්නම් අලුතින් file එකක් හදනවා.
  • 'a' (append): File එකේ අගට අලුත් data එකතු කරන්න open කරනවා. File එක නැත්නම් අලුතින් file එකක් හදනවා.
  • 'b' (binary): Binary mode එකේ open කරන්න (e.g., images, audio files). 'rb', 'wb' වගේ භාවිතා කරනවා.
  • 't' (text): Text mode එකේ open කරන්න. මේක තමයි default mode එක. 'rt' වගේ භාවිතා කරනවා.

අපි හිතමු අපිට my_data.txt කියලා file එකක් කියවන්න ඕනේ කියලා. එතකොට මෙහෙමයි ලියන්නේ:

file_obj = open("my_data.txt", "r")
# File එකෙන් data කියවනවා...
# ...
file_obj.close()

මතක තියාගන්න! File එක open කරාට පස්සේ, වැඩේ ඉවර වුනාම අනිවාර්යයෙන්ම file_obj.close() call කරලා file එක close කරන්න ඕනේ. එහෙම නොකළොත් resource leaks, data corruption වගේ issues එන්න පුළුවන්.

ෆයිල් එක කියවමු - විවිධ ක්‍රම! (Let's Read the File - Different Methods!)

දැන් file එක open කරගත්තා නේද? දැන් අපි බලමු ඒකේ තියෙන data කියවගන්න පුළුවන් විවිධ ක්‍රම මොනවද කියලා.

1. read() - File එකේ හැමදේම කියවන්න

මේ method එකෙන් file එකේ තියෙන හැම character එකක්ම string එකක් විදියට කියවනවා.

file_obj = open("sample.txt", "r")
content = file_obj.read()
print(content)
file_obj.close()

භාවිතය: පොඩි files වල සම්පූර්ණ content එකම කියවන්න ඕනේ නම් මේක ගොඩක් හොඳයි. හැබැයි ලොකු files වලදී මේක භාවිතා කරන එක හොඳ නැහැ, මොකද file එකේ හැමදේම memory එකට load වෙන නිසා.

2. readline() - එක line එකින් එක line එක කියවන්න

මේ method එකෙන් file එකෙන් එක line එකක් විතරක් කියවනවා. හැම line එකකම අන්තිමට newline character එක (\n) එකතු වෙලා තියෙනවා.

file_obj = open("sample.txt", "r")
line1 = file_obj.readline()
line2 = file_obj.readline()
print(line1, end='') # newline character එක අයින් කරන්න end='' පාවිච්චි කරනවා
print(line2, end='')
file_obj.close()

File එකේ හැම line එකක්ම කියවන්න නම් loop එකක් පාවිච්චි කරන්න පුළුවන්.

file_obj = open("sample.txt", "r")
for line in file_obj:
    print(line, end='') # අනවශ්‍ය අමතර හිස් line spaces අයින් කරන්න
file_obj.close()

භාවිතය: ලොකු files වලදී line එකින් line එක process කරන්න මේක ගොඩක්ම හොඳයි, මොකද මුළු file එකම එකපාරට memory එකට load වෙන්නේ නැති නිසා.

3. readlines() - හැම line එකක්ම list එකක් විදියට කියවන්න

මේ method එකෙන් file එකේ තියෙන හැම line එකක්ම කියවලා, ඒ හැම line එකක්ම string එකක් විදියට අඩංගු list එකක් return කරනවා.

file_obj = open("sample.txt", "r")
all_lines = file_obj.readlines()
for line in all_lines:
    print(line, end='')
file_obj.close()

භාවිතය: File එකේ තියෙන හැම line එකක්ම list එකකට දාලා පස්සේ process කරන්න ඕනේ නම් මේක ගොඩක් පහසුයි. හැබැයි මේකත් ලොකු files වලදී memory issues ඇති කරන්න පුළුවන්.

Smart විදියට වැඩ කරමු - The 'with' Statement

මම කලින් කිව්වා නේද, file එකක් open කරාට පස්සේ අනිවාර්යයෙන්ම close කරන්න ඕනේ කියලා. හැබැයි programmer කෙනෙක්ට මේක අමතක වෙන්න පුළුවන්, නැත්නම් file එක open කරලා data කියවන අතරතුර error එකක් ආවොත් file එක close වෙන්නේ නැතුව යන්න පුළුවන්. මේකෙන් resource leaks වෙන්න පුළුවන්. මේ ප්‍රශ්නෙට හොඳම විසඳුම තමයි Python වල තියෙන with statement එක.

with statement එක පාවිච්චි කරනකොට, file එක open කරලා වැඩේ ඉවර වුනාම, එහෙම නැත්නම් error එකක් ආවොත්, Python විසින් automatic වම file එක close කරනවා. මේක හරිම පහසුයි වගේම හොඳ practice එකක්.

with open("sample.txt", "r") as file_obj:
    content = file_obj.read()
    print(content)
# මෙතනට ආවම file_obj එක automatic වම close වෙලා තියෙන්නේ

වැදගත්කම:

  • Automatic Resource Management: ඔයාලට manual file.close() එක ගැන හිතන්න ඕනේ නැහැ.
  • Error Safety: code block එක ඇතුලේ error එකක් ආවත් file එක නිවැරදිව close වෙනවා.

ඔයාලා හැමවෙලේම file operations කරනකොට with statement එක පාවිච්චි කරන්න පුරුදු වෙන්න.

ප්‍රායෝගික උදාහරණයක් - අපිම කරලා බලමු! (A Practical Example - Let's Try It Ourselves!)

දැන් අපි ඉගෙන ගත්ත දේවල් පාවිච්චි කරලා පොඩි real-world scenario එකක් බලමු. හිතන්නකෝ ඔයාලට student data තියෙන text file එකක් තියෙනවා කියලා. අපිට ඕනේ මේක කියවලා, ඒකේ තියෙන student කෙනෙක්ගේ විස්තර separate කරලා print කරන්න.

මුලින්ම, students.txt කියලා file එකක් හදලා මේ data ටික ඒකට දාගමු.

නම: කමල් පෙරේරා
වයස: 30
නගරය: කොළඹ
රැකියාව: මෘදුකාංග ඉංජිනේරු

නම: ආශා සේනාරත්න
වයස: 25
නගරය: මහනුවර
රැකියාව: දත්ත විශ්ලේෂක

නම: සුරංගි ප්‍රියදර්ශනී
වයස: 35
නගරය: ගාල්ල
රැකියාව: ව්‍යාපෘති කළමනාකරු

දැන් අපි Python code එක ලියමු මේ file එක කියවලා process කරන්න.

def process_student_data(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            current_student_data = {}
            student_count = 0
            print(f"\n-- {filename} file එකෙන් කියවන දත්ත --\n")
            for line in f:
                line = line.strip() # line එකේ ඉස්සරහා පිටිපස්සේ තියෙන හිස්තැන් අයින් කරනවා
                if line:
                    if ":" in line:
                        key, value = line.split(':', 1)
                        current_student_data[key.strip()] = value.strip()
                    else:
                        # This handles cases where a line might not contain a ':' but is not empty
                        pass
                else:
                    # Empty line, means a new student record starts
                    if current_student_data:
                        student_count += 1
                        print(f"ශිෂ්‍යයා {student_count}:")
                        for key, value in current_student_data.items():
                            print(f"  {key}: {value}")
                        print("---------------------")
                        current_student_data = {}

            # Process the last student record if file doesn't end with an empty line
            if current_student_data:
                student_count += 1
                print(f"ශිෂ්‍යයා {student_count}:")
                for key, value in current_student_data.items():
                    print(f"  {key}: {value}")
                print("---------------------")

    except FileNotFoundError:
        print(f"Error: '{filename}' file එක හොයාගන්න බැහැ!")
    except Exception as e:
        print(f"Error: දත්ත කියවීමේදී දෝෂයක් සිදුවිය: {e}")

# function එක call කරමු
process_student_data("students.txt")

මේ code එකෙන් මොකද වෙන්නේ?

  1. process_student_data කියන function එකෙන් students.txt file එක open කරනවා.
  2. for line in f: කියන loop එකෙන් line එකින් line එක කියවනවා.
  3. line.strip() වලින් line එකේ මුල සහ අග තියෙන හිස් ඉඩ (whitespace) අයින් කරනවා.
  4. if line: වලින් හිස් නැති line එකක්ද කියලා බලනවා.
  5. if ":" in line: වලින් line එකේ colon (:) එකක් තියෙනවද කියලා බලලා, ඒකෙන් key එකයි value එකයි වෙන් කරලා ගන්නවා.
  6. හිස් line එකක් (else block එක) කියන්නේ student කෙනෙක්ගේ data ඉවර වෙලා අලුත් කෙනෙක්ගේ data පටන් ගන්නවා කියන එක. එතකොට කලින් student ගේ data print කරලා, current_student_data dictionary එක clear කරනවා.
  7. අවසානයේදී FileNotFoundError සහ වෙනත් පොදු errors handle කරන්න try-except block එකක් පාවිච්චි කරලා තියෙනවා.

මේ උදාහරණයෙන් ඔයාලට තේරෙනවා ඇති file එකකින් data කියවලා කොහොමද ඒක practical විදියට process කරන්නේ කියලා. ඔයාලට මේකේ changes කරලා, ඔයාලට ඕනේ විදියට වෙනත් types වල data process කරන්න පුළුවන්.

කරදර ආවොත් - දෝෂ නිරාකරණය සහ හොඳම ක්‍රම (If Troubles Arise - Troubleshooting and Best Practices)

Programming කරනකොට errors එනවා කියන්නේ සාමාන්‍ය දෙයක්. File I/O කරනකොටත් එන common errors කිහිපයක් සහ ඒවා විසඳගන්නෙ කොහොමද කියලා බලමු.

1. FileNotFoundError

මේක තමයි බහුලවම එන error එක. Python වලට ඔයාලා කියපු file එක හොයාගන්න බැරි වුනාම මේ error එක එනවා.

හේතු:

  • File එකේ නම වැරදියි. (e.g., data.txt වෙනුවට date.txt කියලා ලියලා තියෙන්න පුළුවන්)
  • File එක ඔයාලගේ Python script එක තියෙන තැන නැහැ. (Path එක වැරදියි)

විසඳුම්:

  • File එකේ නම හරියටම තියෙනවද කියලා verify කරන්න.
  • File එකේ path එක හරියට දෙන්න. Full path එක (e.g., C:\Users\YourName\Documents\data.txt) දෙන එක වඩාත් සුරක්ෂිතයි, නැත්නම් script එක run කරන folder එකට file එක දාන්න.
  • os.path.exists() වගේ functions පාවිච්චි කරලා file එක තියෙනවද කියලා check කරන්න.
  • try-except block එකක් පාවිච්චි කරලා error එක handle කරන්න. (උදාහරණයක් විදියට උඩ code එකේ තියෙනවා.)

2. Encoding Issues

විශේෂයෙන්ම සිංහල වගේ භාෂාවකින් data තියෙන files කියවනකොට encoding errors එන්න පුළුවන්. ඒ කියන්නේ computer එකට file එකේ තියෙන characters හඳුනාගන්න බැරි වෙන එක.

හේතු:

  • File එක save කරලා තියෙන්නේ වෙනත් encoding එකකින් (e.g., ANSI) Python default එකෙන් (UTF-8) කියවන්න හදනකොට.

විසඳුම්:

  • File එක open කරනකොට encoding parameter එක specify කරන්න. සාමාන්‍යයෙන් 'utf-8' තමයි හොඳම practice එක, මොකද මේක universal standard එකක්.
with open("sinhala_text.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

හොඳම ක්‍රම (Best Practices)

File I/O කරනකොට මේ කරුණු ටික මතක තියාගන්න:

  • Always use with statement: මේක තමයි අංක එක. Automatic closing නිසා resource leaks සහ errors වලදී ඇතිවෙන ගැටළු මගහරවා ගන්න පුළුවන්.
  • Specify Encoding: විශේෂයෙන්ම text files එක්ක වැඩ කරනකොට, encoding='utf-8' විදියට specify කරන එකෙන් character related errors මගහරවා ගන්න පුළුවන්.
  • Handle Errors: try-except block පාවිච්චි කරලා FileNotFoundError වගේ errors handle කරන්න. මේකෙන් ඔයාලගේ program එක crash වෙන එක වළක්වා ගන්න පුළුවන්.
  • Read Smartly: ලොකු files වලදී read() වෙනුවට readline() නැත්නම් for line in file_object: වගේ methods පාවිච්චි කරන්න පුරුදු වෙන්න. මේකෙන් memory usage එක අඩු කරගන්න පුළුවන්.

අවසාන වචනය - වැඩේ ගොඩ දාගමු!

ඉතින් යාලුවනේ, අද අපි Python වලින් files කියවන විදිය ගැන හොඳටම ඉගෙන ගත්තා. open() function එක, විවිධ reading methods (read(), readline(), readlines()), with statement එකේ වැදගත්කම, practical example එකක් වගේම common errors විසඳගන්න විදියත් අපි කතා කළා.

මේ දේවල් ඔයාලා ප්‍රායෝගිකව කරලා බලන එක හරිම වැදගත්. මොකද, programming කියන්නේ කරලාම ඉගෙන ගන්න ඕනේ දෙයක්. ඔයාලගේ computer එකේ පොඩි text file එකක් හදලා, මේ උදාහරණ ටික run කරලා බලන්න. ඒක වෙනස් කරලා, ඔයාලට ඕනේ විදියට data process කරන්න උත්සාහ කරන්න.

දැන් ඔයාලට Python වලින් files කියවන එක එච්චර අමාරු දෙයක් නෙමෙයි කියලා හිතෙනවා ඇති. මේ දැනුම ඔයාලගේ ಮುಂದಿನ software development projects වලට ගොඩක් වැදගත් වෙයි. මතක තියාගන්න, practice makes perfect!

ඔයාලගේ අදහස්, ප්‍රශ්න, නැත්නම් මේ ගැන තියෙන අත්දැකීම් පහළින් කමෙන්ට් කරන්න අමතක කරන්න එපා. මම කැමතියි ඔයාලා එක්ක කතා කරන්න. ඊළඟ පෝස්ට් එකෙන් හම්බවෙමු! ජයවේවා!