CSV failide lugemine

CSV-fail on lihtne teksitfail, milles hoitakse tabelikujulist infot. CSV-failides eraldatakse andmed veergudes erinevate sümbolitega, enamasti komadega. Esimesel real on tavaliselt veergude nimed ning igal järgmisel real on andmed. Eraldavat märki kutsutakse „delimiter“. Näide CSV-failist, kus eraldajaks on koma:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

CSV-failide lugemiseks on vaja teada eraldusmärki.

import csv

# Opens the file.
with open('file.txt') as csv_file:

    # Saves the file as a csv.reader object and separates the lines in file to lists of strings which were separated by the delimiter.
    csv_reader = csv.reader(csv_file, delimiter=',')

    # Loops over each line in file.
    for row in csv_reader:

        # Prints the list of strings in that line.
        print(row)

Selle koodi jooksutamise tulemus:

['name', 'department', 'birthday month']
['John Smith', 'Accounting', 'November']
['Erica Meyers', 'IT', 'March']

Lisalugemist ametlikust dokumentatsioonist: https://docs.python.org/3/library/csv.html