import csv
with open('/path/to/location', 'wb') as f:
writer = csv.writer(f)
writer.writerows(youriterable)
One of them:
import csv
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
In this tutorial, we will learn to write CSV files with different formats in Python with the help of examples.,Now let's see how we can write CSV files in different formats. We will then learn how to customize the csv.writer() function to write them.,The advantage of using dialect is that it makes the program more modular. Notice that we can reuse myDialect to write other CSV files without having to re-specify the CSV format.,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.
We are going to exclusively use the csv
module built into Python for this task. But first, we will have to import the module as :
import csv
Suppose we want to write a CSV file with the following entries:
SN, Name, Contribution 1, Linus Torvalds, Linux Kernel 2, Tim Berners - Lee, World Wide Web 3, Guido van Rossum, Python Programming
Here's how we do it.
import csv
with open('innovators.csv', 'w', newline = '') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
writer.writerow([3, "Guido van Rossum", "Python Programming"])
Example 3: Write CSV File Having Pipe Delimiter
import csv
data_list = [
["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]
]
with open('innovators.csv', 'w', newline = '') as file:
writer = csv.writer(file, delimiter = '|')
writer.writerows(data_list)
Output
SN | Name | Contribution 1 | Linus Torvalds | Linux Kernel 2 | Tim Berners - Lee | World Wide Web 3 | Guido van Rossum | Python Programming
First, open the CSV file for writing (w mode) by using the open() function.,Next, open the CSV file for writing by calling the open() function.,Finally, write data rows to the CSV file using the writerows() method.,If you’re dealing with non-ASCII characters, you need to specify the character encoding in the open() function.
The following code illustrates the above steps:
.wp - block - code { border: 0; padding: 0; } .wp - block - code > div { overflow: auto; } .shcb - language { border: 0; clip: rect(1 px, 1 px, 1 px, 1 px); - webkit - clip - path: inset(50 % ); clip - path: inset(50 % ); height: 1 px; margin: -1 px; overflow: hidden; padding: 0; position: absolute; width: 1 px; word - wrap: normal; word - break: normal; } .hljs { box - sizing: border - box; } .hljs.shcb - code - table { display: table; width: 100 % ; } .hljs.shcb - code - table > .shcb - loc { color: inherit; display: table - row; width: 100 % ; } .hljs.shcb - code - table.shcb - loc > span { display: table - cell; } .wp - block - code code.hljs: not(.shcb - wrap - lines) { white - space: pre; } .wp - block - code code.hljs.shcb - wrap - lines { white - space: pre - wrap; } .hljs.shcb - line - numbers { border - spacing: 0; counter - reset: line; } .hljs.shcb - line - numbers > .shcb - loc { counter - increment: line; } .hljs.shcb - line - numbers.shcb - loc > span { padding - left: 0.75 em; } .hljs.shcb - line - numbers.shcb - loc::before { border - right: 1 px solid #ddd; content: counter(line); display: table - cell; padding: 0 0.75 em; text - align: right; - webkit - user - select: none; - moz - user - select: none; - ms - user - select: none; user - select: none; white - space: nowrap; width: 1 % ; } import csv # open the file in the write mode f = open('path/to/csv_file', 'w') # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row) # close the file f.close() Code language: Python(python)
It’ll be shorter if you use the with
statement so that you don’t need to call the close()
method to explicitly close the file:
import csv # open the file in the write mode with open('path/to/csv_file', 'w') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row) Code language: PHP(php)
The following illustrates how to write UTF-8 characters to a CSV file:
import csv # open the file in the write mode with open('path/to/csv_file', 'w', encoding = 'UTF8') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row) Code language: PHP(php)
To remove the blank line, you pass the keyword argument newline=''
to the open()
function as follows:
import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries.csv', 'w', encoding = 'UTF8', newline = '') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write the data writer.writerow(data) Code language: PHP(php)
The following uses the writerows()
method to write multiple rows into the countries.csv
file:
import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = [ ['Albania', 28748, 'AL', 'ALB'], ['Algeria', 2381741, 'DZ', 'DZA'], ['American Samoa', 199, 'AS', 'ASM'], ['Andorra', 468, 'AD', 'AND'], ['Angola', 1246700, 'AO', 'AGO'] ] with open('countries.csv', 'w', encoding = 'UTF8', newline = '') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write multiple rows writer.writerows(data) Code language: PHP(php)
Last Updated : 22 Jun, 2020
Syntax:
csv.reader(csvfile, dialect = 'excel', ** fmtparams
Output:
[
['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']
]
writerow(fields)
Output:
[
['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']
]
Syntax:
csv.writer(csvfile, dialect = 'excel', ** fmtparams)
writerow(fields)
writerow(fields)
writerows(rows)
Syntax:
writeheader()
The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.,The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.,The Dialect class is a container class whose attributes contain information for how to handle doublequotes, whitespace, delimiters, etc. Due to the lack of a strict CSV specification, different applications produce subtly different CSV data. Dialect instances define how reader and writer instances behave.,Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.
>>>
import csv
>>>
with open('eggs.csv', newline = '') as csvfile:
...spamreader = csv.reader(csvfile, delimiter = ' ', quotechar = '|')
...
for row in spamreader:
...print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
import csv
with open('eggs.csv', 'w', newline = '') as csvfile:
spamwriter = csv.writer(csvfile, delimiter = ' ',
quotechar = '|', quoting = csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
>>>
import csv
>>>
with open('names.csv', newline = '') as csvfile:
...reader = csv.DictReader(csvfile)
...
for row in reader:
...print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese
>>>
print(row) {
'first_name': 'John',
'last_name': 'Cleese'
}
import csv
with open('names.csv', 'w', newline = '') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writeheader()
writer.writerow({
'first_name': 'Baked',
'last_name': 'Beans'
})
writer.writerow({
'first_name': 'Lovely',
'last_name': 'Spam'
})
writer.writerow({
'first_name': 'Wonderful',
'last_name': 'Spam'
})
import csv
with open('students.csv', 'w', newline = '') as csvfile:
writer = csv.writer(csvfile, dialect = 'unix') ^
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
with open('example.csv', newline = '') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) #...process CSV file contents here...