U ovom ćemo tutorialu uz primjere naučiti kako čitati i pisati u CSV datoteke u Pythonu.
CSV (Vrijednosti odvojene zarezom) format je jedan od najjednostavnijih i najčešćih načina za pohranu tabličnih podataka. Da bi predstavljala CSV datoteku, mora se spremiti s nastavkom .csv datoteke.
Uzmimo primjer:
Ako otvorite gornju CSV datoteku pomoću uređivača teksta kao što je uzvišeni tekst, vidjet ćete:
SN, Ime, Grad 1, Michael, New Jersey 2, Jack, Kalifornija
Kao što vidite, elementi CSV datoteke odvojeni su zarezima. Evo ,
graničnika.
Kao graničnik možete imati bilo koji pojedinačni znak prema vašim potrebama.
Napomena: csv modul može se koristiti i za druge nastavke datoteka (poput: .txt ) sve dok je njihov sadržaj u ispravnoj strukturi.
Rad s CSV datotekama u Pythonu
Iako bismo ugrađenu open()
funkciju mogli koristiti za rad s CSV datotekama u Pythonu, postoji namjenski csv
modul koji puno olakšava rad s CSV datotekama.
Prije nego što možemo koristiti metode za csv
modul, prvo moramo uvesti modul koristeći:
import csv
Čitanje CSV datoteka pomoću csv.reader ()
Za čitanje CSV datoteke u Pythonu možemo koristiti csv.reader()
funkciju. Pretpostavimo da u trenutnom direktoriju imamo csv
datoteku imena people.csv sa sljedećim unosima.
Ime | Dob | Profesija |
Utičnica | 23 | Liječnik |
Mlinar | 22 | Inženjer |
Pročitajmo ovu datoteku koristeći csv.reader()
:
Primjer 1: Pročitajte CSV s razdjelnikom zareza
import csv with open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Izlaz
('Ime', 'Dob', 'Zanimanje') ('Jack', '23', 'Liječnik') ('Miller', '22', 'Inženjer')
Ovdje smo otvorili datoteku people.csv u načinu čitanja pomoću:
with open('people.csv', 'r') as file:…
Da biste saznali više o otvaranju datoteka u Pythonu, posjetite: Ulaz / izlaz Python datoteke
Zatim csv.reader()
se koristi za čitanje datoteke koja vraća iterabilni reader
objekt.
Zatim se reader
objekt ponavlja pomoću for
petlje za ispis sadržaja svakog retka.
U gornjem primjeru koristimo csv.reader()
funkciju u zadanom načinu za CSV datoteke s graničnikom zareza.
Međutim, funkcija je puno prilagodljivija.
Pretpostavimo da je naša CSV datoteka koristila tab kao graničnik. Da bismo čitali takve datoteke, csv.reader()
funkciji možemo proslijediti neobavezne parametre . Uzmimo primjer.
Primjer 2: Pročitajte CSV datoteku s razdjelnikom kartice
import csv with open('people.csv', 'r',) as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Primijetite neobavezni parametar delimiter = ' '
u gornjem primjeru.
Kompletna sintaksa csv.reader()
funkcije je:
csv.reader(csvfile, dialect='excel', **optional_parameters)
Kao što možete vidjeti iz sintakse, csv.reader()
funkciju možemo proslijediti i dijalekatski parametar . dialect
Parametar omogućuje nam da se funkcija fleksibilniji. Da biste saznali više, posjetite: Čitanje CSV datoteka u Pythonu.
Pisanje CSV datoteka pomoću csv.writer ()
Za pisanje u CSV datoteku na Pythonu možemo koristiti csv.writer()
funkciju.
csv.writer()
Funkcija vraća writer
objekt koji pretvara korisničkih podataka u razgraničeni niz. Taj se niz kasnije može koristiti za upisivanje u CSV datoteke pomoću writerow()
funkcije. Uzmimo primjer.
Primjer 3: Zapišite u CSV datoteku
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"))
Kada pokrenemo gornji program, kreira se datoteka protagonist.csv sa sljedećim sadržajem:
SN, Film, Protagonist 1, Gospodar prstenova, Frodo Baggins 2, Harry Potter, Harry Potter
U gore navedenom programu otvorili smo datoteku u načinu pisanja.
Zatim smo svaki red proslijedili kao popis. Ti se popisi pretvaraju u razgraničeni niz i zapisuju u CSV datoteku.
Primjer 4: Zapisivanje više redaka s napisima ()
Ako moramo zapisati sadržaj dvodimenzionalnog popisa u CSV datoteku, evo kako to možemo učiniti.
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 tofieldnames
- alist
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")
Ovdje program čita people.csv iz trenutnog direktorija.
Da bismo pisali u CSV datoteku, moramo pozvati to_csv()
funkciju DataFrame-a.
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')
Ovdje smo stvorili DataFrame koristeći pd.DataFrame()
metodu. Zatim to_csv()
se poziva funkcija za ovaj objekt za zapisivanje u person.csv .
Da biste saznali više, posjetite:
- Python pandas.read_csv (službena stranica)
- Python pandas.pandas.DataFrame.to_csv (službena stranica)