Python CSV: leia e grave arquivos CSV

Neste tutorial, aprenderemos como ler e escrever em arquivos CSV em Python com a ajuda de exemplos.

Um formato CSV (Comma Separated Values) é uma das maneiras mais simples e comuns de armazenar dados tabulares. Para representar um arquivo CSV, ele deve ser salvo com a extensão de arquivo .csv .

Vamos dar um exemplo:

Se você abrir o arquivo CSV acima usando um editor de texto, como texto sublime, verá:

 SN, Nome, Cidade 1, Michael, New Jersey 2, Jack, Califórnia 

Como você pode ver, os elementos de um arquivo CSV são separados por vírgulas. Aqui ,está um delimitador.

Você pode ter qualquer caractere único como delimitador de acordo com suas necessidades.

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.

Trabalhar com arquivos CSV em Python

Embora possamos usar a open()função integrada para trabalhar com arquivos CSV em Python, há um csvmódulo dedicado que torna o trabalho com arquivos CSV muito mais fácil.

Antes de usarmos os métodos para o csvmódulo, precisamos primeiro importar o módulo usando:

 import csv 

Lendo arquivos CSV usando csv.reader ()

Para ler um arquivo CSV em Python, podemos usar a csv.reader()função. Suponha que tenhamos um csvarquivo chamado people.csv no diretório atual com as seguintes entradas.

Nome Era Profissão
Jack 23 Médico
Moleiro 22 Engenheiro

Vamos ler este arquivo usando csv.reader():

Exemplo 1: Leia CSV com delimitador de vírgula

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

Resultado

 ('Nome', 'Idade', 'Profissão') ('Jack', '23', 'Médico') ('Miller', '22', 'Engenheiro') 

Aqui, abrimos o arquivo people.csv no modo de leitura usando:

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

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 readerobjeto iterável .

O readerobjeto é então iterado usando um forloop para imprimir o conteúdo de cada linha.

No exemplo acima, estamos usando a csv.reader()função no modo padrão para arquivos CSV com delimitador de vírgula.

No entanto, a função é muito mais personalizável.

Suponha que nosso arquivo CSV estivesse usando tabulação como delimitador. Para ler esses arquivos, podemos passar parâmetros opcionais para a csv.reader()função. Vamos dar um exemplo.

Exemplo 2: Ler arquivo CSV com delimitador de guia

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

Observe o parâmetro opcional delimiter = ' 'no exemplo acima.

A sintaxe completa da csv.reader()função é:

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

Como você pode ver na sintaxe, também podemos passar o parâmetro de dialeto para a csv.reader()função. O dialectparâmetro nos permite tornar a função mais flexível. Para saber mais, visite: Lendo arquivos CSV em Python.

Gravando arquivos CSV usando csv.writer ()

Para escrever em um arquivo CSV em Python, podemos usar a csv.writer()função.

A csv.writer()função retorna um writerobjeto que converte os dados do usuário em uma string delimitada. Esta string pode ser usada posteriormente para gravar em arquivos CSV usando a writerow()função. Vamos dar um exemplo.

Exemplo 3: gravar em um arquivo 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 executamos o programa acima, um arquivo protagonist.csv é criado com o seguinte conteúdo:

 SN, Filme, Protagonista 1, Senhor dos Anéis, Frodo Baggins 2, Harry Potter, Harry Potter 

No programa acima, abrimos o arquivo no modo de escrita.

Em seguida, passamos cada linha como uma lista. Essas listas são convertidas em uma string delimitada e gravadas no arquivo CSV.

Exemplo 4: gravando várias linhas com writerows ()

Se precisarmos gravar o conteúdo da lista bidimensional em um arquivo CSV, veja como podemos fazer isso.

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

Aqui, o programa lê people.csv do diretório atual.

Para gravar em um arquivo CSV, precisamos chamar a to_csv()função de um 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') 

Aqui, criamos um DataFrame usando o pd.DataFrame()método. Em seguida, a to_csv()função para este objeto é chamada, para escrever em person.csv .

Para saber mais, visite:

  • Python pandas.read_csv (site oficial)
  • Python pandas.pandas.DataFrame.to_csv (site oficial)

Artigos interessantes...