Citirea fișierelor CSV în Python

În acest tutorial, vom învăța să citim fișiere CSV cu diferite formate în Python cu ajutorul exemplelor.

Vom folosi exclusiv csvmodulul încorporat în Python pentru această sarcină. Dar mai întâi, va trebui să importăm modulul ca:

 import csv 

Am acoperit deja noțiunile de bază despre modul de utilizare a csvmodulului pentru citirea și scrierea în fișiere CSV. Dacă nu aveți nicio idee despre utilizarea csvmodulului, consultați tutorialul nostru despre Python CSV: Citiți și scrieți fișiere CSV

Utilizarea de bază a csv.reader ()

Să vedem un exemplu de bază de utilizare csv.reader()pentru a vă reîmprospăta cunoștințele existente.

Exemplul 1: Citiți fișiere CSV cu csv.reader ()

Să presupunem că avem un fișier CSV cu următoarele intrări:

 SN, Nume, Contribuția 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Python Programming 

Putem citi conținutul fișierului cu următorul program:

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

Ieșire

 („SN”, „Nume”, „Contribuție”) („1”, „Linus Torvalds”, „Linux Kernel”) („2”, „Tim Berners-Lee”, „World Wide Web”) („3” , „Guido van Rossum”, „Programare Python”) 

Aici am deschis fișierul innovators.csv în modul de citire folosind open()funcția.

Pentru a afla mai multe despre deschiderea fișierelor în Python, vizitați: Intrare / ieșire fișier Python

Apoi, csv.reader()este folosit pentru a citi fișierul, care returnează un readerobiect iterabil .

readerObiectul este apoi iterată folosind o forbuclă pentru a imprima conținutul fiecărui rând.

Acum, vom analiza fișierele CSV cu diferite formate. Vom învăța apoi cum să personalizăm csv.reader()funcția pentru a le citi.

Fișiere CSV cu Delimitatori personalizați

În mod implicit, o virgulă este utilizată ca delimitator într-un fișier CSV. Cu toate acestea, unele fișiere CSV pot utiliza altele decât o virgulă. Puțini dintre cei populari sunt |și .

Să presupunem că fișierul innovators.csv din Exemplul 1 folosea tabul ca delimitator. Pentru a citi fișierul, putem transmite un delimiterparametru suplimentar csv.reader()funcției.

Să luăm un exemplu.

Exemplul 2: Citiți fișierul CSV având tab Delimiter

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

Ieșire

 („SN”, „Nume”, „Contribuție”) („1”, „Linus Torvalds”, „Linux Kernel”) („2”, „Tim Berners-Lee”, „World Wide Web”) („3” , „Guido van Rossum”, „Programare Python”) 

După cum putem vedea, parametrul opțional delimiter = ' 'ajută la specificarea readerobiectului din care fișierul CSV din care citim, are file ca delimitator.

Fișiere CSV cu spații inițiale

Unele fișiere CSV pot avea un caracter spațial după un delimitator. Când folosim csv.reader()funcția implicită pentru a citi aceste fișiere CSV, vom obține spații și în ieșire.

Pentru a elimina aceste spații inițiale, trebuie să trecem un parametru suplimentar numit skipinitialspace. Să vedem un exemplu:

Exemplul 3: Citiți fișiere CSV cu spații inițiale

Să presupunem că avem un fișier CSV numit people.csv cu următorul conținut:

 SN, Nume, Oraș 1, John, Washington 2, Eric, Los Angeles 3, Brad, Texas 

Putem citi fișierul CSV după cum urmează:

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

Ieșire

 („SN”, „Nume”, „Oraș”) („1”, „John”, „Washington”) („2”, „Eric”, „Los Angeles”) („3”, „Brad”, „ Texas') 

Programul este similar cu alte exemple, dar are un skipinitialspaceparametru suplimentar care este setat la True.

Acest lucru permite readerobiectului să știe că intrările au spațiu alb inițial. Ca urmare, spațiile inițiale care erau prezente după un delimitator sunt eliminate.

Fișiere CSV cu ghilimele

Unele fișiere CSV pot avea ghilimele în jurul fiecărei sau a unora dintre intrări.

Let's take quotes.csv as an example, with the following entries:

 "SN", "Name", "Quotes" 1, Buddha, "What we think we become" 2, Mark Twain, "Never regret anything that made you smile" 3, Oscar Wilde, "Be yourself everyone else is already taken" 

Using csv.reader() in minimal mode will result in output with the quotation marks.

In order to remove them, we will have to use another optional parameter called quoting.

Let's look at an example of how to read the above program.

Example 4: Read CSV files with quotes

 import csv with open('person1.csv', 'r') as file: reader = csv.reader(file, quoting=csv.QUOTE_ALL, skipinitialspace=True) for row in reader: print(row) 

Output

 ('SN', 'Name', 'Quotes') ('1', 'Buddha', 'What we think we become') ('2', 'Mark Twain', 'Never regret anything that made you smile') ('3', 'Oscar Wilde', 'Be yourself everyone else is already taken') 

As you can see, we have passed csv.QUOTE_ALL to the quoting parameter. It is a constant defined by the csv module.

csv.QUOTE_ALL specifies the reader object that all the values in the CSV file are present inside quotation marks.

There are 3 other predefined constants you can pass to the quoting parameter:

  • csv.QUOTE_MINIMAL - Specifies reader object that CSV file has quotes around those entries which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.
  • csv.QUOTE_NONNUMERIC - Specifies the reader object that the CSV file has quotes around the non-numeric entries.
  • csv.QUOTE_NONE - Specifies the reader object that none of the entries have quotes around them.

Dialects in CSV module

Notice in Example 4 that we have passed multiple parameters (quoting and skipinitialspace) to the csv.reader() function.

This practice is acceptable when dealing with one or two files. But it will make the code more redundant and ugly once we start working with multiple CSV files with similar formats.

As a solution to this, the csv module offers dialect as an optional parameter.

Dialect helps in grouping together many specific formatting patterns like delimiter, skipinitialspace, quoting, escapechar into a single dialect name.

It can then be passed as a parameter to multiple writer or reader instances.

Example 5: Read CSV files using dialect

Suppose we have a CSV file (office.csv) with the following content:

 "ID"| "Name"| "Email" "A878"| "Alfonso K. Hamby"| "[email protected]" "F854"| "Susanne Briard"| "[email protected]" "E833"| "Katja Mauer"| "[email protected]" 

The CSV file has initial spaces, quotes around each entry, and uses a | delimiter.

Instead of passing three individual formatting patterns, let's look at how to use dialects to read this file.

 import csv csv.register_dialect('myDialect', delimiter='|', skipinitialspace=True, quoting=csv.QUOTE_ALL) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, dialect='myDialect') for row in reader: print(row) 

Output

 ('ID', 'Name', 'Email') ("A878", 'Alfonso K. Hamby', '[email protected]') ("F854", 'Susanne Briard', '[email protected]') ("E833", 'Katja Mauer', '[email protected]') 

From this example, we can see that the csv.register_dialect() function is used to define a custom dialect. It has the following syntax:

 csv.register_dialect(name(, dialect(, **fmtparams))) 

The custom dialect requires a name in the form of a string. Other specifications can be done either by passing a sub-class of Dialect class, or by individual formatting patterns as shown in the example.

While creating the reader object, we pass dialect='myDialect' to specify that the reader instance must use that particular dialect.

The advantage of using dialect is that it makes the program more modular. Notice that we can reuse 'myDialect' to open other files without having to re-specify the CSV format.

Read CSV files with csv.DictReader()

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 a CSV file (people.csv) with the following entries:

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

Using csv.Sniffer class

The Sniffer class is used to deduce the format of a CSV file.

The Sniffer class offers two methods:

  • sniff(sample, delimiters=None) - This function analyses a given sample of the CSV text and returns a Dialect subclass that contains all the parameters deduced.

An optional delimiters parameter can be passed as a string containing possible valid delimiter characters.

  • has_header(sample) - This function returns True or False based on analyzing whether the sample CSV has the first row as column headers.

Let's look at an example of using these functions:

Example 7: Using csv.Sniffer() to deduce the dialect of CSV files

Suppose we have a CSV file (office.csv) with the following content:

 "ID"| "Name"| "Email" A878| "Alfonso K. Hamby"| "[email protected]" F854| "Susanne Briard"| "[email protected]" E833| "Katja Mauer"| "[email protected]" 

Let's look at how we can deduce the format of this file using csv.Sniffer() class:

 import csv with open('office.csv', 'r') as csvfile: sample = csvfile.read(64) has_header = csv.Sniffer().has_header(sample) print(has_header) deduced_dialect = csv.Sniffer().sniff(sample) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, deduced_dialect) for row in reader: print(row) 

Output

 True ('ID', 'Name', 'Email') ('A878', 'Alfonso K. Hamby', '[email protected]') ('F854', 'Susanne Briard', '[email protected]') ('E833', 'Katja Mauer', '[email protected]') 

As you can see, we read only 64 characters of office.csv and stored it in the sample variable.

This sample was then passed as a parameter to the Sniffer().has_header() function. It deduced that the first row must have column headers. Thus, it returned True which was then printed out.

În mod similar, eșantionul a fost transmis și Sniffer().sniff()funcției. A returnat toți parametrii Dialectdeduși ca o subclasă care a fost apoi stocată în variabila deduced_dialect.

Ulterior, am redeschis fișierul CSV și am trecut deduced_dialectvariabila ca parametru către csv.reader().

A fost corect capabil să prezică delimiter, quotingși skipinitialspaceparametri în office.csv fișierul fără a ne menționa în mod explicit ei.

Notă: Modulul csv poate fi utilizat și pentru alte extensii de fișiere (cum ar fi: .txt ), atâta timp cât conținutul lor este într-o structură adecvată.

Lectură recomandată: scrieți în fișiere CSV în Python

Articole interesante...