Python CSV: leer y escribir archivos CSV

En este tutorial, aprenderemos cómo leer y escribir en archivos CSV en Python con la ayuda de ejemplos.

Un formato CSV (valores separados por comas) es una de las formas más simples y comunes de almacenar datos tabulares. Para representar un archivo CSV, debe guardarse con la extensión de archivo .csv .

Tomemos un ejemplo:

Si abre el archivo CSV anterior con un editor de texto como texto sublime, verá:

 SN, Nombre, Ciudad 1, Michael, Nueva Jersey 2, Jack, California 

Como puede ver, los elementos de un archivo CSV están separados por comas. Aquí, ,hay un delimitador.

Puede tener cualquier carácter individual como su delimitador según sus necesidades.

Nota: El módulo csv también se puede utilizar para otras extensiones de archivo (como: .txt ) siempre que su contenido tenga la estructura adecuada.

Trabajar con archivos CSV en Python

Si bien podríamos usar la open()función incorporada para trabajar con archivos CSV en Python, hay un csvmódulo dedicado que facilita mucho el trabajo con archivos CSV.

Antes de que podamos usar los métodos para el csvmódulo, primero debemos importar el módulo usando:

 import csv 

Lectura de archivos CSV con csv.reader ()

Para leer un archivo CSV en Python, podemos usar la csv.reader()función. Supongamos que tenemos un csvarchivo llamado people.csv en el directorio actual con las siguientes entradas.

Nombre Años Profesión
Jack 23 Médico
Molinero 22 Ingeniero

Leamos este archivo usando csv.reader():

Ejemplo 1: leer CSV con delimitador de coma

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

Salida

 ('Nombre', 'Edad', 'Profesión') ('Jack', '23', 'Doctor') ('Miller', '22', 'Ingeniero') 

Aquí, hemos abierto el archivo people.csv en modo de lectura usando:

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

Para obtener más información sobre cómo abrir archivos en Python, visite: Entrada / Salida de archivos de Python

Luego, csv.reader()se usa para leer el archivo, que devuelve un readerobjeto iterable .

El readerobjeto se itera a continuación, utilizando un forbucle para imprimir el contenido de cada fila.

En el ejemplo anterior, estamos usando la csv.reader()función en modo predeterminado para archivos CSV que tienen delimitador de coma.

Sin embargo, la función es mucho más personalizable.

Supongamos que nuestro archivo CSV usa tabulación como delimitador. Para leer dichos archivos, podemos pasar parámetros opcionales a la csv.reader()función. Pongamos un ejemplo.

Ejemplo 2: leer archivo CSV con delimitador de tabulación

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

Observe el parámetro opcional delimiter = ' 'en el ejemplo anterior.

La sintaxis completa de la csv.reader()función es:

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

Como puede ver en la sintaxis, también podemos pasar el parámetro de dialecto a la csv.reader()función. El dialectparámetro nos permite flexibilizar la función. Para obtener más información, visite: Leer archivos CSV en Python.

Escribir archivos CSV con csv.writer ()

Para escribir en un archivo CSV en Python, podemos usar la csv.writer()función.

The csv.writer() function returns a writer object that converts the user's data into a delimited string. This string can later be used to write into CSV files using the writerow() function. Let's take an example.

Example 3: Write to a CSV file

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

When we run the above program, a protagonist.csv file is created with the following content:

 SN,Movie,Protagonist 1,Lord of the Rings,Frodo Baggins 2,Harry Potter,Harry Potter 

In the above program, we have opened the file in writing mode.

Then, we have passed each row as a list. These lists are converted to a delimited string and written into the CSV file.

Example 4: Writing multiple rows with writerows()

If we need to write the contents of the 2-dimensional list to a CSV file, here's how we can do it.

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

Aquí, el programa lee people.csv del directorio actual.

Para escribir en un archivo CSV, necesitamos llamar a la to_csv()función de 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') 

Aquí, hemos creado un DataFrame usando el pd.DataFrame()método. Luego, to_csv()se llama a la función para este objeto, para escribir en person.csv .

Para obtener más información, visite:

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

Articulos interesantes...