Python CSV: branje in pisanje datotek CSV

V tej vadnici bomo s pomočjo primerov izvedeli, kako brati in zapisovati v datoteke CSV v Pythonu.

Oblika CSV (vrednosti, ločene z vejico) je eden najbolj preprostih in najpogostejših načinov shranjevanja tabelarnih podatkov. Če želite predstaviti datoteko CSV, jo je treba shraniti s pripono datoteke .csv .

Vzemimo primer:

Če zgornjo datoteko CSV odprete z urejevalnikom besedila, kot je vzvišeno besedilo, boste videli:

 SN, Ime, Mesto 1, Michael, New Jersey 2, Jack, Kalifornija 

Kot lahko vidite, so elementi datoteke CSV ločeni z vejicami. Tukaj ,je ločilo.

Kot ločilo lahko dobite kateri koli posamezen znak, kot ustreza vašim potrebam.

Opomba: Modul csv se lahko uporablja tudi za druge končnice datotek (na primer: .txt ), če je njihova vsebina v pravilni strukturi.

Delo z datotekami CSV v Pythonu

Čeprav bi lahko vgrajeno open()funkcijo uporabili za delo z datotekami CSV v Pythonu, obstaja namenski csvmodul, ki delo z datotekami CSV olajša.

Preden lahko uporabimo metode za csvmodul, moramo najprej uvoziti modul z uporabo:

 import csv 

Branje datotek CSV z uporabo csv.reader ()

Za branje datoteke CSV v Pythonu lahko uporabimo csv.reader()funkcijo. Recimo, da imamo v trenutnem imeniku csvdatoteko z imenom people.csv z naslednjimi vnosi.

Ime Starost Poklic
Jack 23. Doktor
Miller 22. Inženir

Preberimo to datoteko z uporabo csv.reader():

Primer 1: Preberite CSV z ločevalnikom vejic

 import csv with open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) 

Izhod

 ('Ime', 'Starost', 'Poklic') ('Jack', '23', 'Doctor') ('Miller', '22', 'Engineer') 

Tu smo datoteko people.csv odprli v načinu branja z uporabo:

 with open('people.csv', 'r') as file:… 

Če želite izvedeti več o odpiranju datotek v Pythonu, obiščite: Vnos / izhod datotek Python

Nato csv.reader()se za branje datoteke uporabi, ki vrne readerpredmet , ki ga je mogoče iti .

Nato se readerpredmet ponovi z forzanko za tiskanje vsebine vsake vrstice.

V zgornjem primeru uporabljamo csv.reader()funkcijo v privzetem načinu za datoteke CSV z ločevalnikom vejic.

Vendar pa je funkcija veliko bolj prilagodljiva.

Recimo, da je naša datoteka CSV uporabljala jeziček kot ločilo. Za branje takih datotek lahko csv.reader()funkciji posredujemo neobvezne parametre . Vzemimo primer.

2. primer: Preberite datoteko CSV z ločevalnikom zavihkov

 import csv with open('people.csv', 'r',) as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row) 

Upoštevajte neobvezni parameter delimiter = ' 'v zgornjem primeru.

Celotna sintaksa csv.reader()funkcije je:

 csv.reader(csvfile, dialect='excel', **optional_parameters) 

Kot lahko vidite iz sintakse, lahko funkcijo prenesemo tudi dialektni parameter csv.reader(). dialectParameter nam omogoča, da je funkcija bolj prilagodljiv. Če želite izvedeti več, obiščite: Branje datotek CSV v Pythonu.

Zapisovanje datotek CSV z uporabo csv.writer ()

Za zapis v datoteko CSV v Pythonu lahko uporabimo csv.writer()funkcijo.

csv.writer()Vrne writerobjekt, ki pretvarja uporabnikovih podatkov v omejenem nizu. Ta niz lahko pozneje uporabimo za zapisovanje v datoteke CSV s pomočjo writerow()funkcije. Vzemimo primer.

3. primer: Zapišite v datoteko CSV

 import csv with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter")) 

Ko zaženemo zgornji program, se ustvari datoteka protagonist.csv z naslednjo vsebino:

 SN, film, protagonist 1, Lord of the Rings, Frodo Baggins 2, Harry Potter, Harry Potter 

V zgornjem programu smo datoteko odprli v načinu pisanja.

Nato smo vsako vrstico predali kot seznam. Ti seznami se pretvorijo v ločen niz in zapišejo v datoteko CSV.

Primer 4: Zapisovanje več vrstic z zapiski ()

Če moramo vsebino dvodimenzionalnega seznama zapisati v datoteko CSV, lahko to storimo tako.

 import csv csv_rowlist = (("SN", "Movie", "Protagonist"), (1, "Lord of the Rings", "Frodo Baggins"), (2, "Harry Potter", "Harry Potter")) with open('protagonist.csv', 'w') as file: writer = csv.writer(file) writer.writerows(csv_rowlist) 

The output of the program is the same as in Example 3.

Here, our 2-dimensional list is passed to the writer.writerows() method to write the content of the list to the CSV file.

Example 5: Writing to a CSV File with Tab Delimiter

 import csv with open('protagonist.csv', 'w') as file: writer = csv.writer(file, delimiter = ' ') writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter")) 

Notice the optional parameter delimiter = ' ' in the csv.writer() function.

The complete syntax of the csv.writer() function is:

 csv.writer(csvfile, dialect='excel', **optional_parameters) 

Similar to csv.reader(), you can also pass dialect parameter the csv.writer() function to make the function much more customizable. To learn more, visit: Writing CSV files in Python

Python csv.DictReader() Class

The objects of a csv.DictReader() class can be used to read a CSV file as a dictionary.

Example 6: Python csv.DictReader()

Suppose we have the same file people.csv as in Example 1.

Name Age Profession
Jack 23 Doctor
Miller 22 Engineer

Let's see how csv.DictReader() can be used.

 import csv with open("people.csv", 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(dict(row)) 

Output

 ('Name': 'Jack', ' Age': ' 23', ' Profession': ' Doctor') ('Name': 'Miller', ' Age': ' 22', ' Profession': ' Engineer') 

As we can see, the entries of the first row are the dictionary keys. And, the entries in the other rows are the dictionary values.

Here, csv_file is a csv.DictReader() object. The object can be iterated over using a for loop. The csv.DictReader() returned an OrderedDict type for each row. That's why we used dict() to convert each row to a dictionary.

Notice that, we have explicitly used the dict() method to create dictionaries inside the for loop.

 print(dict(row)) 

Note: Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict() explicitly.

The full syntax of the csv.DictReader() class is:

 csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds) 

To learn more about it in detail, visit: Python csv.DictReader() class

Python csv.DictWriter() Class

The objects of csv.DictWriter() class can be used to write to a CSV file from a Python dictionary.

The minimal syntax of the csv.DictWriter() class is:

 csv.DictWriter(file, fieldnames) 

Here,

  • file - CSV file where we want to write to
  • fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file

Example 7: Python csv.DictWriter()

 import csv with open('players.csv', 'w', newline='') as file: fieldnames = ('player_name', 'fide_rating') writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow(('player_name': 'Magnus Carlsen', 'fide_rating': 2870)) writer.writerow(('player_name': 'Fabiano Caruana', 'fide_rating': 2822)) writer.writerow(('player_name': 'Ding Liren', 'fide_rating': 2801)) 

The program creates a players.csv file with the following entries:

 player_name,fide_rating Magnus Carlsen,2870 Fabiano Caruana,2822 Ding Liren,2801 

The full syntax of the csv.DictWriter() class is:

 csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds) 

To learn more about it in detail, visit: Python csv.DictWriter() class

Using the Pandas library to Handle CSV files

Pandas is a popular data science library in Python for data manipulation and analysis. If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease and efficiency.

Before we can use pandas, we need to install it. To learn more, visit: How to install Pandas?

Once we install it, we can import Pandas as:

 import pandas as pd 

To read the CSV file using pandas, we can use the read_csv() function.

 import pandas as pd pd.read_csv("people.csv") 

Tu program bere people.csv iz trenutnega imenika.

Če želite zapisovati v datoteko CSV, moramo poklicati to_csv()funkcijo DataFrame.

 import pandas as pd # creating a data frame df = pd.DataFrame((('Jack', 24), ('Rose', 22)), columns = ('Name', 'Age')) # writing data frame to a CSV file df.to_csv('person.csv') 

Tu smo z uporabo pd.DataFrame()metode ustvarili DataFrame . Nato to_csv()se pokliče funkcija za ta objekt, ki zapisuje v person.csv .

Če želite izvedeti več, obiščite:

  • Python pandas.read_csv (uradna stran)
  • Python pandas.pandas.DataFrame.to_csv (uradna stran)

Zanimive Članki...