Python CSV: Čtení a zápis souborů CSV

V tomto kurzu se naučíme, jak číst a psát do souborů CSV v Pythonu pomocí příkladů.

Formát CSV (Comma Separated Values) je jedním z nejjednodušších a nejběžnějších způsobů ukládání tabulkových dat. Chcete-li představovat soubor CSV, musí být uložen s příponou .csv .

Vezměme si příklad:

Pokud otevřete výše uvedený soubor CSV pomocí textového editoru, jako je vznešený text, uvidíte:

 SN, Jméno, Město 1, Michael, New Jersey 2, Jack, Kalifornie 

Jak vidíte, prvky souboru CSV jsou odděleny čárkami. Zde ,je oddělovač.

Jako oddělovač můžete mít libovolný znak podle svých potřeb.

Poznámka: Modul csv lze použít i pro jiné přípony souborů (například: .txt ), pokud jsou jejich obsahy ve správné struktuře.

Práce se soubory CSV v Pythonu

I když bychom mohli použít vestavěnou open()funkci pro práci se soubory CSV v Pythonu, existuje speciální csvmodul, díky kterému je práce se soubory CSV mnohem jednodušší.

Než budeme moci použít metody k csvmodulu, musíme nejprve importovat modul pomocí:

 import csv 

Čtení souborů CSV pomocí csv.reader ()

Ke čtení souboru CSV v Pythonu můžeme použít csv.reader()funkci. Předpokládejme, že v aktuálním adresáři máme csvsoubor s názvem people.csv s následujícími položkami.

název Stáří Profese
Zvedák 23 Doktor
Mlynář 22 Inženýr

Přečtěte si tento soubor pomocí csv.reader():

Příklad 1: Číst soubor CSV s oddělovačem čárky

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

Výstup

 ('Jméno', 'Věk', 'Profese') ('Jack', '23', 'Doktor') ('Miller', '22', 'Inženýr') 

Zde jsme otevřeli soubor people.csv v režimu čtení pomocí:

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

Další informace o otevírání souborů v Pythonu najdete na stránce: Vstup / výstup souboru Pythonu

Potom csv.reader()se používá ke čtení souboru, který vrací iterovatelný readerobjekt.

readerObjekt je potom opakována za použití forsmyčky vytisknout obsah každého řádku.

Ve výše uvedeném příkladu používáme csv.reader()funkci ve výchozím režimu pro soubory CSV s oddělovačem čárky.

Funkce je však mnohem přizpůsobitelnější.

Předpokládejme, že náš soubor CSV používal tabulátor jako oddělovač. Abychom takové soubory mohli přečíst, můžeme funkci předat volitelné parametry csv.reader(). Vezměme si příklad.

Příklad 2: Číst soubor CSV s oddělovačem karet

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

Všimněte si volitelného parametru delimiter = ' 've výše uvedeném příkladu.

Úplná syntaxe csv.reader()funkce je:

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

Jak vidíte ze syntaxe, můžeme funkci předat také parametr dialekt csv.reader(). Tento dialectparametr nám umožňuje učinit funkci pružnější. Další informace najdete na stránce: Čtení souborů CSV v Pythonu.

Zápis souborů CSV pomocí csv.writer ()

K zápisu do souboru CSV v Pythonu můžeme použít csv.writer()funkci.

csv.writer()Funkce vrátí writerobjekt, který převádí data uživatele do oddělovači řetězec. Tento řetězec lze později použít k zápisu do souborů CSV pomocí writerow()funkce. Vezměme si příklad.

Příklad 3: Zápis do souboru 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")) 

Když spustíme výše uvedený program, vytvoří se soubor protagonist.csv s následujícím obsahem:

 SN, Film, Protagonista 1, Pán prstenů, Frodo Pytlík 2, Harry Potter, Harry Potter 

Ve výše uvedeném programu jsme soubor otevřeli v režimu psaní.

Poté jsme každý řádek předali jako seznam. Tyto seznamy jsou převedeny na oddělený řetězec a zapsány do souboru CSV.

Příklad 4: Zápis více řádků pomocí Writerows ()

Pokud potřebujeme zapsat obsah dvourozměrného seznamu do souboru CSV, můžeme to udělat takto.

 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") 

Zde program čte soubor people.csv z aktuálního adresáře.

Chcete-li zapisovat do souboru CSV, musíme zavolat to_csv()funkci 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') 

Tady jsme pomocí pd.DataFrame()metody vytvořili DataFrame . Potom to_csv()se volá funkce tohoto objektu, psát do person.csv .

Další informace najdete na adrese:

  • Python pandas.read_csv (oficiální stránky)
  • Python pandas.pandas.DataFrame.to_csv (oficiální stránka)

Zajímavé články...