- How to Create a CSV File Using Python
- How to Create a CSV File Using the csv.writer Class
- The writerow() Method
- The writerows() Method
- How to Create a CSV File Using the csv.DictWriter Class
- The writeheader() Method
- The writerows() Method
- Conclusion
- References and Further Reading
- Как читать и писать CSV-файлы в Python
- Что такое файл CSV?
- Модули для чтения и записи
- csv.reader
- модуль csv.writer
- Классы DictReader и DictWriter
- DictReader
- DictWriter
- Диалекты и форматирование
- Чтение файла CSV
- Чтение CSV-файла с помощью csv.reader
How to Create a CSV File Using Python
Damilola Oladele
CSV is an acronym for comma-separated values. It’s a file format that you can use to store tabular data, such as in a spreadsheet. You can also use it to store data from a tabular database.
You can refer to each row in a CSV file as a data record. Each data record consists of one or more fields, separated by commas.
This article shows you how to use the Python built-in module called csv to create CSV files. In order to fully comprehend this tutorial, you should have a good understanding of the fundamentals of the Python programming language.
The csv module has two classes that you can use in writing data to CSV. These classes are:
How to Create a CSV File Using the csv.writer Class
You can use the csv.writer class to write data into a CSV file. The class returns a writer object, which you can then use to convert data into delimited strings.
To ensure that the newline characters inside the quoted fields interpret correctly, open a CSV file object with newline=».
The syntax for the csv.writer class is as follows:
csv.writer(csvfile, dialect=’excel’, **fmtparams)
Now, let me walk you through the meaning of the different parameters used in the syntax.
- The csvfile parameter represents the csvfile object with the write() method.
- The optional dialect parameter represents the name of the dialect you can use in writing the CSV file.
- The optional fmtparams parameter represents the formatting parameters that you can use to overwrite the parameters specified in the dialect.
The csv.writer class has two methods that you can use to write data to CSV files. The methods are as follows:
The writerow() Method
The writerow() method takes in iterable data as its parameter and then writes the data to your CSV file in a single row. One popular usage of the writerow() method is using it to write the field row of your CSV file.
Now let me show you how you can use the writerow() method to write a single row into your CSV file.
In your code editor, create a file with the name profiles1.py. Then write the following code in the file:
import csv with open('profiles1.csv', 'w', newline='') as file: writer = csv.writer(file) field = ["name", "age", "country"] writer.writerow(field) writer.writerow(["Oladele Damilola", "40", "Nigeria"]) writer.writerow(["Alina Hricko", "23", "Ukraine"]) writer.writerow(["Isabel Walter", "50", "United Kingdom"])
The explanation for the code in profiles1.py is as follows:
- Line one imports the Python csv module.
- Line two is a blank line that separates the imported module from the rest of the code.
- Line three of the code opens the CSV file in writing (w mode) with the help of the open() function.
- Line four creates a CSV writer object by calling the writer() function and stores it in the writer variable.
- Line five creates a variable named fields , which stores a list that consists of strings, each representing the title of a column in the CSV file.
- Line six and below writes the field data and other data to CSV file by calling the writerow() method of the CSV writer object.
Once you are done, go to your command line terminal and navigate to the directory that has the Python file profiles1.py. Run the following command:
You should get a CSV file named profiles1.csv in your working directory with the following text in it:
name,age,country Oladele Damilola,40,Nigeria Alina Hricko,23,Ukraine Isabel Walter,50,United Kingdom
The writerows() Method
The writerows() method has similar usage to the writerow() method. The only difference is that while the writerow() method writes a single row to a CSV file, you can use the writerows() method to write multiple rows to a CSV file.
To see how the writerows() method works, create a file named profiles2.py in your working directory. Then write the following code in the file you created:
import csv with open('profiles2.csv', 'w', newline='') as file: writer = csv.writer(file) row_list = [ ["name", "age", "country"], ["Oladele Damilola", "40", "Nigeria"], ["Alina Hricko", "23" "Ukraine"], ["Isabel Walter", "50" "United Kingdom"], ] writer.writerow(row_list)
After writing the code in your profiles2.py file, go to your command line terminal and run the following command:
Now you should have a CSV file named profiles2.csv in your working directory. The file should have the data in the row_list variable.
How to Create a CSV File Using the csv.DictWriter Class
You can use the csv.DictWriter class to write a CSV file from a dictionary. This is unlike the csv.writer Class, which writes to a CSV file from a list.
The syntax for the csv.DictWriter is as follows:
class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
Now let me explain the meaning of the different parameters in the syntax:
- The csvfile represents the file object with the write() method
- The fieldnames parameter is a sequence of keys that identify the order in which Python passes the values in the dictionary.
- The restval parameter is optional and it specifies the value to be written if the dictionary is missing a key in fieldnames.
- The extrasaction parameter is optional and it specifies the action to take if a key is not found in fieldnames. Setting this parameter to raise , raises a ValueError.
- The dialect parameter is optional and it represents the name of the dialect you want to use.
The csv.DictWriter class has two methods that you can use to write data to CSV files. The methods are as follows:
The writeheader() Method
Use the writeheader() method to write the first row of your csv file using the pre-specified fieldnames .
To see how the the writeheader() method works, create a new file named profiles3.py in your working directory. Then write the following code in the profles3.py file using your code editor:
import csv mydict =[, , ] fields = ['name', 'age', 'country'] with open('profiles3.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames = fields) writer.writeheader()
The explanation of the code in profiles3.py is as follows:
- Line one imports the Python csv module.
- Line two is a blank space that separates the Python csv module from the rest of the code.
- Line three stores a list that contains three different dictionaries in a variable named mydict . The dictionaries have the data of different profiles in them.
- Line seven stores strings, which represent the title of each column of the CSV file that you want to create in a variable named fields .
- Line nine opens the profiles3.csv file in writing mode using open() function.
- The csv.DictWriter() function in line ten creates the CSV dictionary writer object.
- Line twelve passes the list of dictionaries to the writer.writeheader() function to write the pre-defined field names.
Once you are done writing the code, go to your command line terminal and navigate to the directory that has the python file profiles3.py. Run the following command:
Now, you should get a CSV file a named profiles3.csv in your working directory that has the following text in it:
The writerows() Method
The writerows() method has a similar usage as the writeheader() method. You can use the method to write all the rows. The method writes only the values and not the keys.
To use the writerows() method, add this line of code to your code in profiles3.py:
Now delete the profiles3.csv in your working directory and re-run the following command in your command line terminal:
You should now have a new CSV file named profiles3.csv in your working directory that has the following text in it:
name,age,country Kelvin Gates,19,USA Blessing Iroko,25,Nigeria Idong Essien,42,Ghana
Conclusion
Although CSV got its name from a comma, the comma is just a delimiter that separates the data.
You should know that a comma is a popular delimiter you will get in most CSV files. However, the delimiter could also be something else. For instance, you can use a semi-colon to separate the data instead of a comma.
If you like this tutorial, kindly follow me on Twitter and give me a shout out.
References and Further Reading
Как читать и писать CSV-файлы в Python
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)
Параметр 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-файл, который содержит имена учеников и их оценки.
Ниже приведен код для чтения данных в нашем CSV с использованием функции csv.reader и класса csv.DictReader .