Python CSV: leggi e scrivi file CSV

In questo tutorial impareremo come leggere e scrivere in file CSV in Python con l'aiuto di esempi.

Un formato CSV (Comma Separated Values) è uno dei modi più semplici e comuni per memorizzare i dati tabulari. Per rappresentare un file CSV, è necessario salvarlo con l' estensione .csv .

Facciamo un esempio:

Se apri il file CSV sopra utilizzando un editor di testo come il testo sublime, vedrai:

 SN, Nome, Città 1, Michael, New Jersey 2, Jack, California 

Come puoi vedere, gli elementi di un file CSV sono separati da virgole. Ecco ,un delimitatore.

Puoi avere qualsiasi carattere singolo come delimitatore secondo le tue esigenze.

Nota: il modulo csv può essere utilizzato anche per altre estensioni di file (come: .txt ) purché i loro contenuti siano nella struttura corretta.

Lavorare con file CSV in Python

Anche se potremmo usare la open()funzione integrata per lavorare con i file CSV in Python, c'è un csvmodulo dedicato che rende molto più facile lavorare con i file CSV.

Prima di poter utilizzare i metodi per il csvmodulo, dobbiamo prima importare il modulo utilizzando:

 import csv 

Lettura di file CSV utilizzando csv.reader ()

Per leggere un file CSV in Python, possiamo usare la csv.reader()funzione. Supponiamo di avere un csvfile denominato people.csv nella directory corrente con le seguenti voci.

Nome Età Professione
Jack 23 Medico
Mugnaio 22 Ingegnere

Leggiamo questo file usando csv.reader():

Esempio 1: leggere CSV con delimitatore virgola

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

Produzione

 ("Nome", "Età", "Professione") ("Jack", "23", "Dottore") ("Miller", "22", "Ingegnere") 

Qui, abbiamo aperto il file people.csv in modalità di lettura utilizzando:

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

Per ulteriori informazioni sull'apertura di file in Python, visitare: Input / output file Python

Quindi, csv.reader()viene utilizzato per leggere il file, che restituisce un readeroggetto iterabile .

L' readeroggetto viene quindi iterato utilizzando un forciclo per stampare il contenuto di ogni riga.

Nell'esempio sopra, stiamo usando la csv.reader()funzione in modalità predefinita per i file CSV con delimitatore virgola.

Tuttavia, la funzione è molto più personalizzabile.

Supponiamo che il nostro file CSV usasse tab come delimitatore. Per leggere tali file, possiamo passare parametri opzionali alla csv.reader()funzione. Facciamo un esempio.

Esempio 2: leggere un file CSV con delimitatore di tabulazione

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

Notare il parametro opzionale delimiter = ' 'nell'esempio precedente.

La sintassi completa della csv.reader()funzione è:

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

Come puoi vedere dalla sintassi, possiamo anche passare il parametro dialetto alla csv.reader()funzione. Il dialectparametro ci permette di rendere la funzione più flessibile. Per saperne di più, visita: Lettura di file CSV in Python.

Scrittura di file CSV utilizzando csv.writer ()

Per scrivere in un file CSV in Python, possiamo usare la csv.writer()funzione.

La csv.writer()funzione restituisce un writeroggetto che converte i dati dell'utente in una stringa delimitata. Questa stringa può essere successivamente utilizzata per scrivere nei file CSV utilizzando la writerow()funzione. Facciamo un esempio.

Esempio 3: scrivere in un file 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")) 

Quando eseguiamo il programma precedente, viene creato un file protagonist.csv con il seguente contenuto:

 SN, Film, Protagonista 1, Il Signore degli Anelli, Frodo Baggins 2, Harry Potter, Harry Potter 

Nel programma sopra, abbiamo aperto il file in modalità di scrittura.

Quindi, abbiamo passato ogni riga come un elenco. Questi elenchi vengono convertiti in una stringa delimitata e scritti nel file CSV.

Esempio 4: scrittura di più righe con writerows ()

Se dobbiamo scrivere il contenuto dell'elenco bidimensionale in un file CSV, ecco come possiamo farlo.

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

Qui, il programma legge people.csv dalla directory corrente.

Per scrivere in un file CSV, dobbiamo chiamare la to_csv()funzione di un 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') 

Qui, abbiamo creato un DataFrame utilizzando il pd.DataFrame()metodo. Quindi, to_csv()viene chiamata la funzione per questo oggetto, per scrivere in person.csv .

Per saperne di più, visita:

  • Python pandas.read_csv (sito ufficiale)
  • Python pandas.pandas.DataFrame.to_csv (sito ufficiale)

Articoli interessanti...