Neste tutorial, aprenderemos a ler arquivos CSV com diferentes formatos em Python com a ajuda de exemplos.
Usaremos exclusivamente o csv
módulo integrado ao Python para essa tarefa. Mas primeiro, teremos que importar o módulo como:
import csv
Já cobrimos os princípios básicos de como usar o csv
módulo para ler e gravar em arquivos CSV. Se você não tem ideia de como usar o csv
módulo, confira nosso tutorial sobre Python CSV: Ler e escrever arquivos CSV
Uso básico de csv.reader ()
Vejamos um exemplo básico de csv.reader()
como atualizar seu conhecimento existente.
Exemplo 1: ler arquivos CSV com csv.reader ()
Suponha que temos um arquivo CSV com as seguintes entradas:
SN, Nome, Contribuição 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Python Programming
Podemos ler o conteúdo do arquivo com o seguinte programa:
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Resultado
('SN', 'Nome', 'Contribuição') ('1', 'Linus Torvalds', 'Linux Kernel') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Programação Python')
Aqui, abrimos o arquivo innovators.csv no modo de leitura usando a open()
função.
Para saber mais sobre como abrir arquivos em Python, visite: Entrada / Saída de Arquivos Python
Em seguida, o csv.reader()
é usado para ler o arquivo, que retorna um reader
objeto iterável .
O reader
objeto é então iterado usando um for
loop para imprimir o conteúdo de cada linha.
Agora, veremos arquivos CSV com diferentes formatos. Em seguida, aprenderemos como personalizar a csv.reader()
função para lê-los.
Arquivos CSV com delimitadores personalizados
Por padrão, uma vírgula é usada como delimitador em um arquivo CSV. No entanto, alguns arquivos CSV podem usar delimitadores diferentes de vírgulas. Poucos são os populares |
e
.
Suponha que o arquivo innovators.csv no Exemplo 1 estava usando tab como delimitador. Para ler o arquivo, podemos passar um delimiter
parâmetro adicional para a csv.reader()
função.
Vamos dar um exemplo.
Exemplo 2: Ler arquivo CSV com delimitador de guia
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Resultado
('SN', 'Nome', 'Contribuição') ('1', 'Linus Torvalds', 'Linux Kernel') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Programação Python')
Como podemos ver, o parâmetro opcional delimiter = ' '
ajuda a especificar o reader
objeto do qual o arquivo CSV que estamos lendo, tem tabulações como delimitador.
Arquivos CSV com espaços iniciais
Alguns arquivos CSV podem ter um caractere de espaço após um delimitador. Quando usamos a csv.reader()
função padrão para ler esses arquivos CSV, obteremos espaços na saída também.
Para remover esses espaços iniciais, precisamos passar um parâmetro adicional chamado skipinitialspace
. Vamos ver um exemplo:
Exemplo 3: leia arquivos CSV com espaços iniciais
Suponha que temos um arquivo CSV denominado people.csv com o seguinte conteúdo:
SN, Nome, Cidade 1, John, Washington 2, Eric, Los Angeles 3, Brad, Texas
Podemos ler o arquivo CSV da seguinte maneira:
import csv with open('people.csv', 'r') as csvfile: reader = csv.reader(csvfile, skipinitialspace=True) for row in reader: print(row)
Resultado
('SN', 'Nome', 'Cidade') ('1', 'John', 'Washington') ('2', 'Eric', 'Los Angeles') ('3', 'Brad', ' Texas ')
O programa é semelhante a outros exemplos, mas tem um skipinitialspace
parâmetro adicional que é definido como True.
Isso permite que o reader
objeto saiba que as entradas possuem um espaço em branco inicial. Como resultado, os espaços iniciais que estavam presentes após um delimitador são removidos.
Arquivos CSV com aspas
Alguns arquivos CSV podem ter aspas em torno de cada uma ou algumas das entradas.
Vamos pegar quotes.csv como exemplo, com as seguintes entradas:
"SN", "Nome", "Citações" 1, Buda, "O que pensamos que nos tornamos" 2, Mark Twain, "Nunca se arrependa de nada que o tenha feito sorrir" 3, Oscar Wilde, "Seja você mesmo, todo mundo já está tomado"
Usar csv.reader()
no modo mínimo resultará em saída entre aspas.
Para removê-los, teremos que usar outro parâmetro opcional chamado quoting
.
Vejamos um exemplo de como ler o programa acima.
Exemplo 4: ler arquivos CSV com aspas
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)
Resultado
('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
- Specifiesreader
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 thereader
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 aDialect
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 returnsTrue
orFalse
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.
Da mesma forma, a amostra também foi passada para a Sniffer().sniff()
função. Ele retornou todos os parâmetros deduzidos como uma Dialect
subclasse que foi então armazenada na variável deduced_dialect.
Posteriormente, reabrimos o arquivo CSV e passamos a deduced_dialect
variável como um parâmetro para csv.reader()
.
Foi corretamente capaz de prever delimiter
, quoting
e skipinitialspace
parâmetros no office.csv arquivo sem nós mencioná-los explicitamente.
Observação: o módulo csv também pode ser usado para outras extensões de arquivo (como: .txt ), desde que seu conteúdo esteja na estrutura adequada.
Leitura recomendada: Grave em arquivos CSV em Python