Leer archivos CSV en Python

En este tutorial, aprenderemos a leer archivos CSV con diferentes formatos en Python con la ayuda de ejemplos.

Vamos a utilizar exclusivamente el csvmódulo integrado en Python para esta tarea. Pero primero, tendremos que importar el módulo como:

 import csv 

Ya hemos cubierto los conceptos básicos de cómo usar el csvmódulo para leer y escribir en archivos CSV. Si no tiene idea sobre cómo usar el csvmódulo, consulte nuestro tutorial sobre Python CSV: Leer y escribir archivos CSV

Uso básico de csv.reader ()

Veamos un ejemplo básico de uso csv.reader()para actualizar su conocimiento existente.

Ejemplo 1: leer archivos CSV con csv.reader ()

Supongamos que tenemos un archivo CSV con las siguientes entradas:

 SN, Nombre, Contribución 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Programación Python 

Podemos leer el contenido del archivo con el siguiente programa:

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

Salida

 ('SN', 'Nombre', 'Contribución') ('1', 'Linus Torvalds', 'Kernel de Linux') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Programación Python') 

Aquí, hemos abierto el archivo innovators.csv en modo de lectura usando open()function.

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.

Ahora, veremos archivos CSV con diferentes formatos. Luego aprenderemos cómo personalizar la csv.reader()función para leerlos.

Archivos CSV con delimitadores personalizados

De forma predeterminada, se utiliza una coma como delimitador en un archivo CSV. Sin embargo, algunos archivos CSV pueden usar delimitadores que no sean una coma. Son pocos los populares |y .

Suponga que el archivo innovators.csv del Ejemplo 1 usa tabulación como delimitador. Para leer el archivo, podemos pasar un delimiterparámetro adicional a la csv.reader()función.

Pongamos un ejemplo.

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

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

Salida

 ('SN', 'Nombre', 'Contribución') ('1', 'Linus Torvalds', 'Kernel de Linux') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Programación Python') 

Como podemos ver, el parámetro opcional delimiter = ' 'ayuda a especificar el readerobjeto del que el archivo CSV que estamos leyendo tiene pestañas como delimitador.

Archivos CSV con espacios iniciales

Algunos archivos CSV pueden tener un carácter de espacio después de un delimitador. Cuando usamos la csv.reader()función predeterminada para leer estos archivos CSV, también obtendremos espacios en la salida.

Para eliminar estos espacios iniciales, necesitamos pasar un parámetro adicional llamado skipinitialspace. Veamos un ejemplo:

Ejemplo 3: leer archivos CSV con espacios iniciales

Supongamos que tenemos un archivo CSV llamado people.csv con el siguiente contenido:

 SN, Nombre, Ciudad 1, John, Washington 2, Eric, Los Ángeles 3, Brad, Texas 

Podemos leer el archivo CSV de la siguiente manera:

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

Salida

 ('SN', 'Nombre', 'Ciudad') ('1', 'John', 'Washington') ('2', 'Eric', 'Los Ángeles') ('3', 'Brad', ' Texas') 

El programa es similar a otros ejemplos, pero tiene un skipinitialspaceparámetro adicional que se establece en True.

Esto permite que el readerobjeto sepa que las entradas tienen espacios en blanco iniciales. Como resultado, se eliminan los espacios iniciales que estaban presentes después de un delimitador.

Archivos CSV con comillas

Algunos archivos CSV pueden tener comillas alrededor de todas o algunas de las entradas.

Tomemos quotes.csv como ejemplo, con las siguientes entradas:

 "SN", "Nombre", "Citas" 1, Buda, "Lo que creemos que nos convertimos" 2, Mark Twain, "Nunca te arrepientas de nada que te haya hecho sonreír" 3, Oscar Wilde, "Sé tú mismo, todos los demás ya están ocupados" 

El uso csv.reader()en modo mínimo dará como resultado una salida con las comillas.

Para eliminarlos, tendremos que usar otro parámetro opcional llamado quoting.

Veamos un ejemplo de cómo leer el programa anterior.

Ejemplo 4: leer archivos CSV con comillas

 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) 

Salida

 ('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.

Del mismo modo, la muestra también se pasó a la Sniffer().sniff()función. Devolvió todos los parámetros deducidos como una Dialectsubclase que luego se almacenó en la variable deduced_dialect.

Más tarde, volvimos a abrir el archivo CSV y pasamos la deduced_dialectvariable como parámetro a csv.reader().

Correctamente fue capaz de predecir delimiter, quotingy skipinitialspaceparámetros en el office.csv archivo sin nosotros describiendo explícitamente.

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.

Lectura recomendada: escribir en archivos CSV en Python

Articulos interesantes...