Home » Writing CSV files in Python

Writing CSV files in Python

In this article, we will learn about writing a csv file in python.

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas.

The use of the comma as a field separator is the source of the name for this file format.

A CSV file typically stores tabular data (numbers and text) in plain text, in which case each line will have the same number of fields.

We will look at the CSV module first

CSV Module

Here are the functions that are available in this module

  • csv.field_size_limit – return maximum field size
  • csv.get_dialect – get the dialect which is associated with the name
  • csv.list_dialects – show all registered dialects
  • csv.reader – read data from a csv file
  • csv.register_dialect – associate dialect with name
  • csv.writer – write data to a csv file
  • csv.unregister_dialect – delete the dialect associated with the name the dialect registry
  • csv.QUOTE_ALL – Quote everything, regardless of type.
  • csv.QUOTE_MINIMAL – Quote fields with special characters
  • csv.QUOTE_NONNUMERIC – Quote all fields that aren’t numbers value
  • csv.QUOTE_NONE – Don’t quote anything in output

 

Writing CSV Files

csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().

writerow(): This method writes a single row at a time. Field row can be written using this method.

Syntax:

writerow(fields)

writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.

Syntax:

Writing CSV files in Python
writerows(rows)

When you have a set of data that you would like to store in a CSV file you use the writer() function. To iterate the data over the rows(lines), you  use the writerow() function.

Consider the following example. We write data into a file “Countries2.csv” where the delimiter is an apostrophe.

 

#import modules
import csv

with open('Countries2.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    #way to write to csv file
    writer.writerow(['Entry', 'Country', 'Capital'])
    writer.writerow(['1', 'France', 'Paris'])
    writer.writerow(['2', 'Germany', 'Berlin'])
    writer.writerow(['3', 'Spain', 'Madrid'])
    writer.writerow(['4', 'Italy', 'Rome'])
    writer.writerow(['5', 'UK', 'London'])

In this example we use writerow to create the field names and then use writerows to create the data, this example creates the same csv file as above

# writing to CSV
import csv 

# field names 
fields = ['Entry', 'Country', 'Capital'] 
    
# data rows of csv file 
rows = [ ['1', 'France', 'Paris'], 
         ['2', 'Germany', 'Berlin'], 
         ['3', 'Spain', 'Madrid'], 
         ['4', 'Italy', 'Rome'], 
         ['5', 'UK', 'London']] 
    
# name of csv file 
filename = "countries1.csv"
    
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv writer object 
    csvwriter = csv.writer(csvfile) 
        
    # writing the fields 
    csvwriter.writerow(fields) 
        
    # writing the data rows 
    csvwriter.writerows(rows)

Writing a csv file with Pandas

Pandas is not part of the Python standard library, so you will need to install it with the pip package manager.

from pandas import DataFrame
C = {'Entry': ['1','2', '3', '4', '5'],
        'Country': ['France', 'Germany', 'Spain', 'Italy', 'UK'],
        'Capital': ['Paris', 'Berlin', 'Madrid', 'Rome', 'London'],
    }
df = DataFrame(C, columns= ['Entry', 'Country', 'Capital'])
export_csv = df.to_csv (r'countriespandas.csv', index = None, header=True) # here you have to write path, where result file will be stored
print (df)

Links

you can get the code on github

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More