Чтение файлов CSV в Python

В этом руководстве мы научимся читать файлы CSV в разных форматах на Python с помощью примеров.

Мы собираемся использовать csvдля этой задачи исключительно модуль, встроенный в Python. Но сначала нам нужно будет импортировать модуль как:

 import csv 

Мы уже рассмотрели основы того, как использовать csvмодуль для чтения и записи в файлы CSV. Если вы не знаете, как использовать csvмодуль, ознакомьтесь с нашим руководством по Python CSV: чтение и запись файлов CSV.

Базовое использование csv.reader ()

Давайте посмотрим на базовый пример использования, csv.reader()чтобы освежить ваши знания.

Пример 1: чтение файлов CSV с помощью csv.reader ()

Предположим, у нас есть CSV-файл со следующими записями:

 SN, имя, вклад 1, Линус Торвальдс, ядро ​​Linux 2, Тим Бернерс-Ли, World Wide Web 3, Гвидо ван Россум, программирование на Python 

Мы можем прочитать содержимое файла с помощью следующей программы:

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

Вывод

 ('SN', 'Имя', 'Вклад') ('1', 'Линус Торвальдс', 'Ядро Linux') ('2', 'Тим Бернерс-Ли', 'Всемирная паутина') ('3' , 'Гвидо ван Россум', 'Программирование на Python') 

Здесь мы открыли файл Innovators.csv в режиме чтения с помощью open()функции.

Чтобы узнать больше об открытии файлов в Python, посетите: Python File Input / Output

Затем csv.reader()используется для чтения файла, который возвращает повторяемый readerобъект.

Затем readerобъект повторяется с использованием forцикла для печати содержимого каждой строки.

Теперь мы рассмотрим файлы CSV с разными форматами. Затем мы узнаем, как настроить csv.reader()функцию для их чтения.

Файлы CSV с настраиваемыми разделителями

По умолчанию в CSV-файле в качестве разделителя используется запятая. Однако в некоторых файлах CSV могут использоваться другие разделители, кроме запятой. Немногие популярные - это |и .

Предположим , что innovators.csv файл в примере 1 , был используя вкладку в качестве разделителя. Чтобы прочитать файл, мы можем передать функции дополнительный delimiterпараметр csv.reader().

Возьмем пример.

Пример 2: Чтение CSV-файла с разделителем табуляции

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

Вывод

 ('SN', 'Имя', 'Вклад') ('1', 'Линус Торвальдс', 'Ядро Linux') ('2', 'Тим Бернерс-Ли', 'Всемирная паутина') ('3' , 'Гвидо ван Россум', 'Программирование на Python') 

Как мы видим, необязательный параметр delimiter = ' 'помогает указать readerобъект, из которого CSV-файл, который мы читаем, имеет табуляции в качестве разделителя.

CSV-файлы с начальными пробелами

В некоторых файлах CSV после разделителя может стоять пробел. Когда мы используем csv.reader()функцию по умолчанию для чтения этих файлов CSV, мы также получим пробелы в выводе.

Чтобы удалить эти начальные пробелы, нам нужно передать дополнительный параметр с именем skipinitialspace. Давайте посмотрим на пример:

Пример 3: чтение файлов CSV с начальными пробелами

Предположим, у нас есть файл CSV с именем people.csv со следующим содержимым:

 СН, Имя, Город 1, Джон, Вашингтон 2, Эрик, Лос-Анджелес 3, Брэд, Техас 

Мы можем прочитать файл CSV следующим образом:

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

Вывод

 ('SN', 'Имя', 'Город') ('1', 'Джон', 'Вашингтон') ('2', 'Эрик', 'Лос-Анджелес') ('3', 'Брэд', ' Техас ') 

Программа похожа на другие примеры, но имеет дополнительный skipinitialspaceпараметр, для которого установлено значение True.

Это позволяет readerобъекту знать, что в записях есть начальные пробелы. В результате первоначальные пробелы, которые присутствовали после разделителя, удаляются.

CSV-файлы с кавычками

Некоторые файлы CSV могут содержать кавычки вокруг каждой или некоторых записей.

В качестве примера возьмем файл quotes.csv со следующими записями:

 «SN», «Имя», «Цитаты» 1, Будда, «То, чем мы думаем, мы стали» 2, Марк Твен, «Никогда не сожалей ни о чем, что заставило тебя улыбнуться» 3, Оскар Уайльд, «Будь собой, все остальные уже заняты» 

Использование csv.reader()в минимальном режиме приведет к выводу в кавычках.

Чтобы удалить их, нам нужно будет использовать еще один необязательный параметр с именем quoting.

Давайте посмотрим на примере того, как читать вышеуказанную программу.

Пример 4. Чтение файлов CSV с кавычками

 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) 

Вывод

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

Аналогичным образом в Sniffer().sniff()функцию был передан образец . Он возвратил все выведенные параметры как Dialectподкласс, который затем был сохранен в переменной deduced_dialect.

Позже мы повторно открыли CSV-файл и передали deduced_dialectпеременную в качестве параметра в csv.reader().

Он правильно рассчитал delimiter, quotingи skipinitialspaceпараметры в office.csv файл без нас оговаривая их.

Примечание. Модуль csv также можно использовать для других расширений файлов (например, .txt ), если их содержимое имеет правильную структуру.

Рекомендуемая литература: запись в файлы CSV на Python

Интересные статьи...