Python වලින් CSV File කියවමු, ලියමු - SC Guide | Python CSV Tutorial Sinhala

Python වලින් CSV File කියවමු, ලියමු - SC Guide | Python CSV Tutorial Sinhala

ආයුබෝවන් හැමෝටම! කොහොමද ඉතින්? අද අපි කතා කරන්න යන්නේ ඔයාලා හැමෝටම ගොඩක් වැදගත් වෙන, දත්ත එක්ක වැඩ කරනකොට නැතුවම බැරි දෙයක් ගැන – ඒ තමයි CSV Files (Comma Separated Values Files). මම දන්නවා අපේ ගොඩක් අය මේ වගේ files එක්ක වැඩ කරලා ඇති. Data Analysis කරන කෙනෙක්ට, Report හදන කෙනෙක්ට, එහෙමත් නැත්නම් පොඩි Software එකකට data load කරන කෙනෙක්ට CSV කියන්නේ නැතුවම බැරි දෙයක්.

ශ්‍රී ලංකාවේ වුණත්, බැංකු වල, රජයේ ආයතන වල, පොඩි Business වල වුණත් ගොඩක් වෙලාවට Data Transfer කරන්න, Export කරන්න use කරන්නේ CSV files. ඒ වගේම Excel files වුණත් CSV විදියට save කරන්න පුළුවන් නිසා, මේක තවත් ජනප්‍රිය වෙලා තියෙනවා. ඉතින්, අපි බලමු කොහොමද Python Programming Language එක use කරලා මේ CSV files එක්ක ලේසියෙන්ම වැඩ කරන්නේ කියලා. අද අපි වැඩි අවධානයක් යොමු කරන්නේ Python වල built-in csv module එකට.

මේ ලිපිය කියෙව්වට පස්සේ ඔයාට පුළුවන් වෙයි, ඕනෑම CSV file එකකින් data කියවන්න (read කරන්න), ඒ වගේම අලුත් data CSV file එකකට ලියන්න (write කරන්න). ඒ වගේම, මේ වැඩ කරනකොට එන පොඩි පොඩි ගැටළු, ඒවට විසඳුම්, සහ හොඳම පුරුදු (best practices) මොනවද කියලත් අපි කතා කරමු. එහෙනම්, වැඩි කතා නැතුව පටන් ගමු නේද!

CSV කියන්නේ මොකක්ද? (What is a CSV File?)

සරලවම කිව්වොත්, CSV (Comma Separated Values) file එකක් කියන්නේ Plain Text file එකක්. ඒ කියන්නේ මේක notepad එකකින් වුණත්, ඕනෑම text editor එකකින් වුණත් open කරලා බලන්න පුළුවන්. මේකේ තියෙන data ටික organize කරලා තියෙන්නේ commas (,) වලින් වෙන් කරලා. හැම line එකක්ම file එකේ තියෙන data record එකක් විදියට ගන්න පුළුවන්. ඒ වගේම, හැම line එකකම තියෙන commas වලින් වෙන් කරපු කොටස් ටික අදාල record එකේ fields (columns) විදියට හඳුන්වන්න පුළුවන්.

උදාහරණයක් විදියට පහල තියෙන CSV file එක බලන්න:

Name,Age,City
Kasun,30,Colombo
Amara,25,Galle
Nimal,35,Kandy

මේකේ, Name,Age,City කියන්නේ headers, එහෙමත් නැත්නම් columns වල නම්. ඊට පස්සේ තියෙන Kasun,30,Colombo වගේ ඒවා data records. මේකේ commas වලින් වෙන් කරලා තියෙනවා නේද? ඒක තමයි Comma Separated Values කියන්නේ. CSV files ගොඩක් වෙලාවට Data Exchange කරන්න use කරනවා. Database එකකින් data export කරලා තවත් Software එකකට import කරනකොට CSV format එක ගොඩක් ප්‍රයෝජනවත් වෙනවා.

මේවා plain text නිසා, වෙනත් platform (Windows, macOS, Linux) වල වුණත්, වෙනත් programming language (Java, C#, PHP) වල වුණත් පහසුවෙන් කියවන්න (read කරන්න) සහ ලියන්න (write කරන්න) පුළුවන්. ඒක තමයි මේ CSV වල තියෙන ලොකුම වාසියක්. ඉතින්, අපි බලමු Python වලින් මේක කොහොමද handle කරන්නේ කියලා.

Python වල csv module එකෙන් වැඩ කරමු (Working with Python's csv Module)

Python වලට CSV files එක්ක වැඩ කරන්න පුළුවන් built-in csv module එකක් තියෙනවා. මේ module එකෙන් CSV files read කරන්නයි, write කරන්නයි අවශ්‍ය හැම පහසුකමක්ම සපයනවා. අපි මුලින්ම බලමු CSV file එකකින් data කියවන්නේ කොහොමද කියලා.

CSV File එකකින් Data කියවීම (Reading Data from a CSV File)

CSV file එකකින් data කියවන්න නම්, මුලින්ම ඒ file එක open කරන්න ඕනේ. Python වල file open කරන්න open() function එක use කරනවා. open() function එකට file එකේ path එකයි, mode එකයි (read කරන්න නම් 'r', write කරන්න නම් 'w', append කරන්න නම් 'a') දෙන්න ඕනේ. CSV files කියවනකොට newline='' කියන parameter එකත් දාන්න මතක තියාගන්න. මේක නැති වුණොත් හිස් lines (blank rows) හැදෙන්න පුළුවන්.

csv.reader භාවිතය (Using csv.reader)

සරලම විදියට CSV file එකක් කියවන්න පුළුවන් csv.reader object එක use කරලා. මේකෙන් CSV file එකේ හැම line එකක්ම list එකක් විදියට අපිට දෙනවා.

මුලින්ම අපි කියවන්න අවශ්‍ය CSV file එක හදාගමු. අපි මේක save කරමු employees.csv නමින්:

name,age,department,salary
Amara,30,HR,60000
Bandara,25,IT,75000
Chathura,35,Finance,80000
Dilini,28,Marketing,55000

දැන් බලමු මේක Python වලින් කියවන්නේ කොහොමද කියලා:

import csv

# CSV file එක කියවීම
try:
    with open('employees.csv', 'r', newline='', encoding='utf-8') as csvfile:
        csv_reader = csv.reader(csvfile)

        # පළමු line එක skip කරන්න පුළුවන් headers තිබ්බොත්
        # next(csv_reader)

        print("Data from employees.csv:")
        for row in csv_reader:
            print(row) # හැම row එකක්ම list එකක් විදියට print වෙනවා

except FileNotFoundError:
    print("Error: employees.csv file not found.")
except Exception as e:
    print(f"An error occurred: {e}")

මේ Code එක run කරාම ඔයාලට output එක මේ වගේ ලැබෙයි:

Data from employees.csv:
['name', 'age', 'department', 'salary']
['Amara', '30', 'HR', '60000']
['Bandara', '25', 'IT', '75000']
['Chathura', '35', 'Finance', '80000']
['Dilini', '28', 'Marketing', '55000']

දැක්කා නේද? හැම line එකක්ම වෙන වෙනම list එකක් විදියට ආවා. Header row එකත් ආවා. Header row එක skip කරන්න ඕන නම්, next(csv_reader) කියන line එක uncomment කරන්න පුළුවන්.

CSV File එකකට Data ලිවීම (Writing Data to a CSV File)

දැන් අපි බලමු Python වලින් කොහොමද අලුත් data CSV file එකකට ලියන්නේ කියලා. Data ලියනකොට open() function එකට 'w' (write) mode එක දෙන්න ඕනේ. කලින් වගේම newline='' parameter එක මෙතනත් වැදගත්. ලිවීම සඳහා අපි csv.writer object එක use කරනවා.

csv.writer භාවිතය (Using csv.writer)

csv.writer object එකෙන් data ලියන්න methods දෙකක් තියෙනවා: writerow() සහ writerows().

  • writerow(row): එක row එකක් ලියන්න. මේකට list එකක් දෙන්න ඕනේ.
  • writerows(rows): එකපාර data rows ගණනාවක් ලියන්න. මේකට lists වලින් හැදුණු list එකක් දෙන්න ඕනේ.

උදාහරණයක් බලමු:

import csv

# ලියන්න අවශ්‍ය data
data_to_write = [
    ['product_id', 'product_name', 'price'],
    ['P001', 'Laptop', 120000],
    ['P002', 'Mouse', 2500],
    ['P003', 'Keyboard', 7000]
]

# CSV file එකට data ලිවීම
try:
    with open('products.csv', 'w', newline='', encoding='utf-8') as csvfile:
        csv_writer = csv.writer(csvfile)

        # Header row එකයි අනිත් data row ටිකයි එකපාර ලියන්න
        csv_writer.writerows(data_to_write)
    
    print("products.csv file created successfully with data.")

except Exception as e:
    print(f"An error occurred while writing to CSV: {e}")

මේ Code එක run කරාම, ඔයාලාගේ project folder එකේ products.csv කියලා අලුත් file එකක් හැදෙයි. ඒක open කරලා බැලුවොත් මේ වගේ data තියෙනවා දකින්න පුළුවන්:

product_id,product_name,price
P001,Laptop,120000
P002,Mouse,2500
P003,Keyboard,7000

හරිම ලේසියි නේද? ඔය විදියට අපිට ඕන නම් data එකින් එක writerow() use කරලත් ලියන්න පුළුවන්:

import csv

# ලියන්න අවශ්‍ය data
new_product = ['P004', 'Monitor', 45000]

try:
    # 'a' (append) mode එකෙන් කලින් තිබ්බ data නැති නොවී අලුත් data add කරන්න පුළුවන්
    with open('products.csv', 'a', newline='', encoding='utf-8') as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow(new_product)
    
    print("New product added to products.csv.")

except Exception as e:
    print(f"An error occurred while appending to CSV: {e}")

මේක run කරලා products.csv එක බැලුවොත්, අන්තිමට P004,Monitor,45000 කියන line එක add වෙලා තියෙනවා දකින්න පුළුවන්.

ප්‍රායෝගික උපදෙස් සහ ගැටළු විසඳීම (Practical Tips and Troubleshooting)

CSV files එක්ක වැඩ කරනකොට පොඩි පොඩි ගැටළු එන්න පුළුවන්. ඒ වගේම වැඩේ තවත් පහසු කරගන්න පුළුවන් tricks ටිකකුත් තියෙනවා. අපි ඒ ගැන කතා කරමු.

Delimiter ගැටළු (Delimiter Issues)

අපේ නමෙන්ම කියනවා වගේ, CSV files වල values වෙන් කරන්නේ commas (,) වලින්. ඒත්, හැම වෙලේම එහෙම වෙන්නේ නෑ. සමහර වෙලාවට semicolon (;) නැත්නම් tab (\t) වගේ වෙන character එකකින් values වෙන් කරලා තියෙන්න පුළුවන්. මේ වගේ අවස්ථාවලදී අපේ code එක වැඩ කරන්නේ නෑ, මොකද default delimiter එක comma එක නිසා.

මේකට විසඳුම තමයි csv.reader සහ csv.writer objects හදනකොට delimiter parameter එක use කරන එක. අපි උදාහරණයක් බලමු, semicolon වලින් වෙන් කරපු CSV file එකක් කියවන හැටි.

අපි students.csv කියලා file එකක් හදාගමු (semicolon වලින් වෙන් කරලා):

id;name;grade
1;Saman;A
2;Kamala;B
3;Nuwan;A-

දැන් මේක කියවමු:

import csv

try:
    with open('students.csv', 'r', newline='', encoding='utf-8') as csvfile:
        # Delimiter එක semicolon (;) විදියට specify කරනවා
        csv_reader = csv.reader(csvfile, delimiter=';') 
        
        print("\nData from students.csv (semicolon delimited):")
        for row in csv_reader:
            print(row)

except FileNotFoundError:
    print("Error: students.csv file not found.")
except Exception as e:
    print(f"An error occurred: {e}")

මේක run කරාම ඔයාලට හරි විදියට data ටික list විදියට ලැබෙයි:

Data from students.csv (semicolon delimited):
['id', 'name', 'grade']
['1', 'Saman', 'A']
['2', 'Kamala', 'B']
['3', 'Nuwan', 'A-']

මේ වගේම, අපිට අවශ්‍ය නම් data ලියනකොටත් වෙන delimiter එකක් use කරන්න පුළුවන්. csv.writer එකටත් delimiter parameter එක දෙන්න පුළුවන්.

import csv

data_to_write_semicolon = [
    ['user_id', 'username', 'email'],
    ['U001', 'john.doe', '[email protected]'],
    ['U002', 'jane.smith', '[email protected]']
]

try:
    with open('users_semicolon.csv', 'w', newline='', encoding='utf-8') as csvfile:
        csv_writer = csv.writer(csvfile, delimiter=';') # Semicolon delimiter
        csv_writer.writerows(data_to_write_semicolon)
    
    print("\nusers_semicolon.csv created with semicolon delimiter.")

except Exception as e:
    print(f"An error occurred: {e}")

මේකෙන් හැදෙන users_semicolon.csv file එකේ data semicolon වලින් වෙන් වෙලා තියෙයි.

Headers එක්ක වැඩ කිරීම (Handling Headers)

ගොඩක් CSV files වල, file එකේ මුල්ම line එකේ තියෙන්නේ columns වල නම් (headers). csv.reader එකෙන් මේ headers සාමාන්‍ය data row එකක් විදියට තමයි කියවන්නේ. ඒත්, අපිට අවශ්‍ය වෙන්නේ data ටික dictionary එකක් විදියට access කරන්න නම්, column name එකෙන් data එක ගන්න පුළුවන් නම් වැඩේ තවත් ලේසියි නේද? මේකට තමයි csv.DictReader සහ csv.DictWriter use කරන්නේ.

csv.DictReader භාවිතය (Using csv.DictReader)

csv.DictReader එකෙන් CSV file එකේ හැම row එකක්ම dictionary එකක් විදියට කියවනවා. මෙතනදී keys විදියට use කරන්නේ header names ටික. මේක ගොඩක්ම convenient, මොකද අපිට index වලින් නොවී column name එකෙන් data access කරන්න පුළුවන්.

import csv

# employees.csv file එක කලින් වගේම තිබේ නම්
# name,age,department,salary
# Amara,30,HR,60000
# Bandara,25,IT,75000
# Chathura,35,Finance,80000
# Dilini,28,Marketing,55000

try:
    with open('employees.csv', 'r', newline='', encoding='utf-8') as csvfile:
        csv_reader = csv.DictReader(csvfile)
        
        print("\nData from employees.csv (using DictReader):")
        for row in csv_reader:
            # දැන් අපිට column name එකෙන් data access කරන්න පුළුවන්
            print(f"Name: {row['name']}, Age: {row['age']}, Dept: {row['department']}, Salary: {row['salary']}")
            # print(row) # මේක print කරොත් හැම row එකක්ම dictionary එකක් විදියට print වෙනවා
            
except FileNotFoundError:
    print("Error: employees.csv file not found.")
except Exception as e:
    print(f"An error occurred: {e}")

මේක run කරාම output එක මේ වගේ ලැබෙයි:

Data from employees.csv (using DictReader):
Name: Amara, Age: 30, Dept: HR, Salary: 60000
Name: Bandara, Age: 25, Dept: IT, Salary: 75000
Name: Chathura, Age: 35, Dept: Finance, Salary: 80000
Name: Dilini, Age: 28, Dept: Marketing, Salary: 55000

දැන් බලන්න, row['name'] වගේ දීලා අපිට ඕන කරන column එකේ data එක ගන්න පුළුවන්. මේක ගොඩක්ම practical. ඒ වගේම, csv.DictReader එක auto detect කරනවා header row එක. ඒ නිසා next(csv_reader) කියල දාන්න අවශ්‍ය වෙන්නේ නෑ.

csv.DictWriter භාවිතය (Using csv.DictWriter)

ඒ වගේම, dictionary data CSV file එකකට ලියන්න csv.DictWriter use කරන්න පුළුවන්. මේකේදී අපි fieldnames කියන parameter එකෙන් headers මොනවද කියලා specify කරන්න ඕනේ. මේකෙන් CSV file එකට ලියනකොට column order එකත් අපිට control කරන්න පුළුවන්.

import csv

# ලියන්න අවශ්‍ය headers
field_names = ['student_id', 'student_name', 'major', 'gpa']

# ලියන්න අවශ්‍ය data (dictionaries list එකක් විදියට)
student_data = [
    {'student_id': 'S001', 'student_name': 'Akila', 'major': 'Computer Science', 'gpa': 3.8},
    {'student_id': 'S002', 'student_name': 'Malini', 'major': 'Business Management', 'gpa': 3.5},
    {'student_id': 'S003', 'student_name': 'Tharindu', 'major': 'Engineering', 'gpa': 3.9}
]

try:
    with open('students_dict.csv', 'w', newline='', encoding='utf-8') as csvfile:
        csv_writer = csv.DictWriter(csvfile, fieldnames=field_names)
        
        # Header row එක ලියන්න
        csv_writer.writeheader()
        
        # Data rows ලියන්න
        csv_writer.writerows(student_data)
    
    print("\nstudents_dict.csv created successfully using DictWriter.")

except Exception as e:
    print(f"An error occurred while writing with DictWriter: {e}")

මේක run කරාම හැදෙන students_dict.csv file එක බලන්න:

student_id,student_name,major,gpa
S001,Akila,Computer Science,3.8
S002,Malini,Business Management,3.5
S003,Tharindu,Engineering,3.9

දැක්කා නේද? writeheader() method එකෙන් header row එක automatically add වෙනවා, ඒ වගේම writerows() එකෙන් dictionaries ටික අදාල columns වලට හරියටම add වෙනවා. මේක data manipulation වලට ගොඩක්ම පහසුයි.

Encoding ගැටළු (Encoding Issues)

සමහර වෙලාවට CSV files කියවනකොට UnicodeDecodeError වගේ errors එන්න පුළුවන්. ඒකට හේතුව තමයි file එක save කරලා තියෙන encoding එකයි, අපි Python වලින් read කරන්න හදන encoding එකයි match නොවෙන එක. ගොඩක් වෙලාවට 'utf-8' කියන encoding එක use කරන එක හොඳයි, මොකද ඒක standard එකක්. ඒත්, සමහර පරණ systems වලින් generate වෙන files වල 'cp1252', 'latin1' වගේ encodings තියෙන්න පුළුවන්.

මේකට විසඳුම තමයි open() function එකේ encoding parameter එක හරියට specify කරන එක. උඩ තිබ්බ හැම code example එකකම මම encoding='utf-8' කියලා දීලා තියෙන්නේ ඒකයි. ඔයාට error එකක් ආවොත්, ඒ encoding එක වෙනස් කරලා try කරලා බලන්න පුළුවන්. උදාහරණයක් විදියට:

# encoding එක වෙනස් කරලා try කරන විදිය
# with open('my_data.csv', 'r', newline='', encoding='cp1252') as csvfile:
#    ...

ගොඩක් වෙලාවට utf-8 හොඳටම ඇති, විශේෂයෙන් සිංහල data තියෙන files එක්ක වැඩ කරනකොටත් utf-8 තමයි හොඳම.

හොඳම පුරුදු (Best Practices)

ඔයාලා දැන් දන්නවා කොහොමද CSV files එක්ක Python වලින් වැඩ කරන්නේ කියලා. දැන් අපි බලමු මේ වැඩ කරනකොට අනිවාර්යයෙන්ම follow කරන්න ඕනේ best practices මොනවද කියලා.

1. with open(...) statement එක භාවිතය (Always Use with open(...))

මම මේ ලිපියේ තිබ්බ හැම code example එකකම with open(...) as file: කියන statement එක use කරා. මේක ගොඩක්ම වැදගත්. මොකද, මේකෙන් file එකත් එක්ක වැඩ කරලා ඉවර වුණාම, file එක automatically close කරනවා. ඔයා file.close() කියලා දාන්න අමතක වුණත්, with statement එකෙන් ඒක බලාගන්නවා. මේක resource management වලට ගොඩක් වැදගත්.

2. csv module එකම භාවිතය (Use the csv Module for Structured CSV Data)

සමහර අය CSV files කියවන්න .split(',') වගේ string methods use කරනවා. ඒත් ඒක එච්චරම හොඳ පුරුද්දක් නෙමෙයි. මොකද, CSV file එකක data එකක (field එකක) ඇතුලෙම comma එකක් තියෙන්න පුළුවන් (උදා: "Colombo, Sri Lanka"). මේ වගේ වෙලාවට .split(',') වලින් හරි විදියට data වෙන් වෙන්නේ නෑ. ඒත් csv module එකෙන් මේ වගේ complications handle කරන්න පුළුවන්. ඒ නිසා, structured CSV data එක්ක වැඩ කරනකොට හැම වෙලේම csv module එකම use කරන්න.

3. newline='' parameter එක භාවිතය (Remember newline='')

open() function එකේ newline='' parameter එක දාන්න අමතක කරන්න එපා. මේකෙන් CSV file කියවනකොට හෝ ලියනකොට ඇති වෙන්න පුළුවන් extra blank rows (හිස් lines) නැති කරනවා. මේක CSV module එකේ documentation එකේම specify කරලා තියෙන වැදගත් දෙයක්.

4. Encoding ගැන සැලකිලිමත් වීම (Be Mindful of Encoding)

උඩත් කිව්වා වගේ, encoding='utf-8' කියන එක standard එකක්. ඒත් ඔයාට UnicodeDecodeError වගේ errors ආවොත්, file එකේ actual encoding එක හොයාගෙන ඒක use කරන්න. Notepad++ වගේ editors වලින් file එකේ encoding එක මොකක්ද කියලා බලන්න පුළුවන්.

5. Error Handling (වැරදි හසුරුවීම)

File operations කරනකොට errors එන්න පුළුවන්. File එක නැති වෙන්න (FileNotFoundError), permissions නැති වෙන්න, data format එක වැරදි වෙන්න වගේ දේවල් වෙන්න පුළුවන්. මේ වගේ අවස්ථාවලදී try-except blocks use කරලා errors handle කරන එක හොඳ පුරුද්දක්. මම මේ ලිපියේ තිබ්බ හැම code example එකකම ඒක කරලා තියෙනවා. මේකෙන් ඔයාගේ application එක crash වෙන එක වළක්වාගෙන, user ට meaningful message එකක් දෙන්න පුළුවන්.

අවසානය (Conclusion)

ඉතින් මචන්ලා, මේ ලිපියෙන් ඔයාලා ගොඩක් දේවල් ඉගෙන ගත්තා කියලා හිතනවා. Python වල csv module එක use කරලා CSV files read කරන හැටි, write කරන හැටි, ඒ වගේම delimiter issues, header handling, encoding වගේ ගැටළු විසඳන හැටිත්, best practices ටිකකුත් අපි විස්තරාත්මකව කතා කළා.

දත්ත එක්ක වැඩ කරන ඕනෑම කෙනෙක්ට, විශේෂයෙන් Software Engineers, Data Analysts, සහ Developers ලට මේ දැනුම ගොඩක් වැදගත් වෙයි. මේ වගේ පොඩි පොඩි දේවල් වලින් තමයි ලොකු Projects හදන්නේ, ඒ වගේම දත්ත කළමනාකරණය කරනකොට මේ වගේ file operations වලට හොඳ අවබෝධයක් තියෙන එක අනිවාර්යයි.

අද ඉගෙන ගත්ත දේවල් ඔයාලාම Try කරලා බලන්න. පොඩි CSV file එකක් හදාගෙන ඒක කියවලා බලන්න, අලුත් data ටිකක් ඒකට ලියලා බලන්න, Delimiter එකක් වෙනස් කරලා try කරන්න. මොනවා හරි ප්‍රශ්න තියෙනවා නම්, එහෙමත් නැත්නම් ඔයාට තියෙන අදහස් Share කරන්න ඕනේ නම්, පහලින් Comment Section එකේ අනිවාර්යයෙන්ම දාන්න. මම පුළුවන් ඉක්මනට ඒවට උත්තර දෙන්නම්.

ඒ වගේම, මේ ලිපිය ඔයාලට වැදගත් වුණා නම්, අනිත් යාළුවන්ටත් share කරන්න අමතක කරන්න එපා. තවත් මේ වගේ වැදගත් ලිපියකින් හමුවෙමු! හැමෝටම ජය වේවා!