How to import csv in python

Как читать и писать CSV-файлы в Python

Esther Vaati

Esther Vaati Last updated Dec 5, 2017

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

Что такое файл CSV?

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

  • импорт и экспорт данных клиентов
  • импорт и экспорт продукции
  • экспорт заказов
  • экспорт аналитических отчетов по электронной коммерции

Модули для чтения и записи

Модуль CSV имеет несколько функций и классов, доступных для чтения и записи CSV, и они включают в себя:

  • функция csv.reader
  • функция csv.writer
  • класс csv.Dictwriter
  • класс csv.DictReader

csv.reader

Модуль csv.reader принимает следующие параметры:

  • csvfile : обычно это объект, который поддерживает протокол итератора и обычно возвращает строку каждый раз, когда вызывается его метод __next__() .
  • dialect=’excel’: необязательный параметр, используемый для определения набора параметров, специфичных для определенного диалекта CSV.
  • fmtparams : необязательный параметр, который можно использовать для переопределения существующих параметров форматирования.

Вот пример того, как использовать модуль csv.reader.

with open('example.csv', newline='') as File: 

модуль csv.writer

Этот модуль похож на модуль csv.reader и используется для записи данных в CSV. Требуется три параметра:

  • csvfile : это может быть любой объект с методом write() .
  • dialect = ‘excel’ : необязательный параметр, используемый для определения набора параметров, специфичных для конкретного CSV.
  • fmtparam : необязательный параметр, который можно использовать для переопределения существующих параметров форматирования.

Классы DictReader и DictWriter

DictReader и DictWriter — это классы, доступные в Python для чтения и записи в CSV. Хотя они и похожи на функции чтения и записи, эти классы используют объекты словаря для чтения и записи в CSV-файлы.

DictReader

Он создает объект, который отображает прочитанную информацию в словарь, ключи которого задаются параметром fieldnames . Этот параметр является необязательным, но если он не указан в файле, данные первой строки становятся ключами словаря.

with open('name.csv') as csvfile: 
reader = csv.DictReader(csvfile) 
print(row['first_name'], row['last_name']) 

DictWriter

Этот класс аналогичен классу DictWriter и выполняет противоположную функцию: запись данных в файл CSV. Класс определяется как csv.DictWriter(csvfile, fieldnames,restval=», extrasaction=’raise’,dialect=’excel’, *args, **kwds)

Читайте также:  Php input name переменная

Параметр fieldnames определяет последовательность ключей, которые определяют порядок, в котором значения в словаре записываются в файл CSV. В отличие от DictReader, этот ключ не является обязательным и должен быть определен во избежание ошибок при записи в CSV.

Диалекты и форматирование

Диалект — это вспомогательный класс, используемый для определения параметров для конкретного экземпляра reader или writer . Диалекты и параметры форматирования должны быть объявлены при выполнении функции чтения или записи.

Есть несколько атрибутов, которые поддерживаются диалектом:

  • delimiter: строка, используемая для разделения полей. По умолчанию это ‘,’ .
  • double quote: Управляет тем, как должны появляться в кавычках случаи, когда кавычки появляются внутри поля. Может быть True или False.
  • escapechar: строка, используемая автором для экранирования разделителя, если в кавычках задано значение QUOTE_NONE .
  • lineterminator: строка, используемая для завершения строк, созданных writer . По умолчанию используется значение ‘\r\n’ .
  • quotechar: строка, используемая для цитирования полей, содержащих специальные символы. По умолчанию это ‘»‘ .
  • skipinitialspace: Если установлено значение True , любые пробелы, следующие сразу за разделителем, игнорируются.
  • strict: если установлено значение True , возникает Error при неправильном вводе CSV.
  • quoting: определяет, когда следует создавать кавычки при чтении или записи в CSV.

Чтение файла CSV

Давайте посмотрим, как читать CSV-файл, используя вспомогательные модули, которые мы обсуждали выше.

Создайте свой CSV-файл и сохраните его как example.csv. Убедитесь, что он имеет расширение .csv и заполните некоторые данные. Здесь у нас есть CSV-файл, который содержит имена учеников и их оценки.

Creating a spreadsheet to generate a CSV

Ниже приведен код для чтения данных в нашем CSV с использованием функции csv.reader и класса csv.DictReader .

Чтение CSV-файла с помощью csv.reader

Источник

Python Import CSV

Python Import CSV

In this article, we will see CSV is elaborated as comma-separated-values which is used to store tabular data or spreadsheet file format, which uses comma as delimiter or separator, and such files are known as CSV files. In Python, to parse or work with such CSV files, we need to import the CSV module, an inbuilt module. To do this, we need to use the “import” keyword before “csv” to support CSV files or to parse CSV files in python. This csv module in Python is used to read or write or handle CSV files; to read or write such files, we need to loop through the CSV file rows.

Web development, programming languages, Software testing & others

Working of CSV Module in Python

In this article, we will see how to import the csv module in Python. In Python, csv is an inbuilt module used to support CSV files, such as reading CSV files. Therefore to extract data from a CSV file, we have to loop through rows, and we also have to use split methods to extract data from each column which are separated by commas.

Now let us see how to import the csv module.

Читайте также:  Абстрактные классы python это

This statement is used for importing a csv module that is used for parsing tabular like data structure such as data in excel format, and these files are saved in .csv extension; this csv modules provide various classes for reading and writing data to CSV files. Now we will see various csv module functions and classes in the below section.

Examples to Implement Python Import CSV

Below are the examples of Python Import CSV:

Example #1

Reading CSV File using CSV Module Function as csv.reader()

This function is used to extract data from CSV files to read and print the output screen data. To do this, we need to create a reader object; then, the function will read each line of the CSV file and make the list of columns and print it. We can read CSV files that are separated from any other delimiter other than comma-separated files.

Now will see how to read CSV file and is demonstrated in the below example:

import csv print("Program to demonstrate csv.reader() function:") print("\n") c = open('company.csv','r') print("The csv file is opened for reading:") print("\n") o = csv.reader(c) print("The contents of the above file is as follows:") for r in o: print (r) c.close()

Python Import CSV Example 1

Explanation: In the above program, we can see we are reading file company.csv, which is already present in the current directory where the python software is present using an open() function with read mode ‘r’. and the output displays the content of the file. This function gives No such file or directory as an error message if the file does not exist.

Example #2 – Writing to the File using csv.writer()

This function is used to write the data to the file. This function can also be used to create a new file and open it in the write mode ‘w’. Let us demonstrate this function in the below example.

import csv print("Program to demonstrate csv.writer() function") print("\n") p_details =[('course','fees','place'),('Python',22000,'Pune'),('Android',11000,'Assam'),('Java',30000,'Delhi')] c = open('programs.csv','w') print("File is opened for writing:") o = csv.writer(c) for p in p_details: o.writerow(p) c.close()

Python Import CSV Example 2

Python Import CSV Example 3

Explanation: In the above program, we can see we are writing details of programming courses, and we have opened a file named ‘programs.csv’ in write mode ‘w’, which first creates a file, and then the details are written to the file. And in the output screen, we can see it will print saying the file is opened for writing, and when we open the file, we can see it in CSV format as shown in the above screenshot, where each data is written in separate columns and row. Note that CSV uses excel as the default output to display the CSV file.

We will now see classes provided by the Python csv module for reading from and writing to a CSV file. DictReader and DictWriter are similar to reader and writer functions as in the above section. But these classes use dictionary objects to read and write CSV files. Now will see these classes in the below section.

Читайте также:  Php cookie закрытие браузера

Example #3 – DictReader

This class uses a dictionary object which is created for mapping the data to read it to the dictionary whose key is given by field names, but if the keys are not defined or declared, then by default, it will take first row data as keys of the dictionary. Let us demonstrate in the below example.

import csv print("Program to demonstrate DictReader() class") print("\n") with open('company.csv') as c: r = csv.DictReader(c) for row in r: print(row['Name'], row['Age'])

Example #3.1 - DictReader

DictReader

Explanation: In the above program, we can see that we are using DictReader() function, which will read the file company.csv, and this will print only those which keys are specified, such as “Name” and “Age” are the keys of the dictionary which is a company.csv file content. So in the above screenshot of output, only the contents of “Name” and “age” are displayed.

Example #4 – DictWriter

This class is also similar to the writer() function. In this class, this also specifies the keys of the dictionary through “fieldnames” as these keys are optional in the above DictReader, but keys are must be specified to avoid ambiguity when writing the data to the CSV file.

Let us demonstrate in the below example.

import csv print("Program to demonstarte DictWriter() class") print("\n") with open('Game.csv', 'w') as file: columnnames = ['Game_name', 'No_of_players'] writer = csv.DictWriter(file, fieldnames=columnnames) writer.writeheader() writer.writerow() writer.writerow() writer.writerow()

demonstrate in the below

DictWriter

Explanation: In the above program, we can see we have created a new file “Game.csv” in write mode “w” by using an open() function, and then we use DictWriter() to write the data to the file, and here we mention the column names as field names which are the keys for the dictionary created. In the above output, we can see how the file is created and the data is written to it.

Conclusion

This article concludes that the CSV module in Python is used to work with CSV(comma separated values) files. CSV modules are also used in many applications in the data science subjects using the pandas concept in Python. This article saw how to read from and write to CSV files using this csv module. In this, we also saw a few CSV functions such as reader() and writer() functions and classes such as DictReader() and DictWriter(), which are created as dictionaries along with keys as field names.

This is a guide to Python Import CSV. Here we discuss a brief overview of Python Import CSV and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –

Источник

Оцените статью