How To Read And Write CSV File In Python

The python csv module provides functions to operate CSV files. This article will show you some examples of how to use the python csv module to read, write CSV files.

1. How To Read CSV Files In Python.

  1. Import python csv module.
    >>> import csv
  2. Open the CSV file by specified file path with reading mode.
    >>> csv_file = open('csv_user_info.csv','r')
  3. Create the CSV file reader object by the python csv module’s reader function.
    >>> csv_reader = csv.reader(csv_file)
  4. Loop in the csv_reader object to get and print each line of text in the CSV file.
    >>> for row in csv_reader:
    ...     print(row)
    ... 
    ["'Name'", "'Email'", "'Title'"]
    ["'jerry'", "'[email protected]'", "'CEO'"]
    ["'tom'", "'[email protected]'", "'Developer'"]

2. How To Write Data To CSV File In Python.

  1. Import the python csv module.
    >>> import csv
  2. Open a file for writing CSV data into it.
    >>> csv_file = open('test.csv','w')
  3. Create a CSV file writer object with the python csv module writer method.
    >>> csv_writer = csv.writer(csv_file, delimiter=';')
  4. Call the csv_writer object’s writerow method to write text into it.
    >>> csv_writer.writerow('I love python')
  5. Invoke the file object’s flush method to save the text to the CSV file, otherwise, you can not find the text data in the CSV file.
    >>> csv_file.flush()
  6. When you open the above CSV file in a text editor, you can find every single character will be separated by the ; separator.
    I; ;l;o;v;e; ;p;y;t;h;o;n

3. How To Read CSV File Data Into Python Dictionary Object.

  1. Import the python csv module, and open the CSV file by the file path.
    >>> import csv
    >>> 
    >>> csv_file = open('csv_user_info.csv','r')
  2. Create the csv reader object by the python csv module DictReader method.
    >>> csv_reader = csv.DictReader(csv_file)
  3. Read each row in the CSV file to a python dictionary object, and print the dictionary object.
    >>> for row in csv_reader:
    ...     print(row)
    ... 
    OrderedDict([("'Name'", "'jerry'"), ("'Email'", "'[email protected]'"), ("'Title'", "'CEO'")])
    OrderedDict([("'Name'", "'tom'"), ("'Email'", "'[email protected]'"), ("'Title'", "'Developer'")])

4. How To Write Python Dictionary Object Data Into CSV File.

  1. Import the python csv module and create a python dictionary object with data.
    >>> import csv
    >>> 
    >>> dict_obj = [{'Title':'CEO', 'Salary':'10000'},{'Title':'Manager','Salary':'9000'} ]
  2. Create CSV file row headers in a python list.
    >>> csv_headers = ['Title', 'Salary']
  3. Open a file to write CSV data into it.
    >>> csv_file = open('test-dict.csv','w')
  4. Invoke the python csv module’s DictWriter method to create a CSV writer object. Pass the CSV file path and the CSV file row headers list.
    >>> csv_writer = csv.DictWriter(csv_file, fieldnames = csv_headers)
  5. Write the CSV row headers and python dictionary object to the CSV file.
    >>> csv_writer.writeheader()
    >>> 
    >>> csv_writer.writerows(dict_obj)
  6. Do not forget to invoke the file object’s flush method to save the changes to the CSV file.
    >>> csv_file.flush()
  7. Below is the CSV file content.
    Title,Salary
    CEO,10000
    Manager,9000

5. How To Use Pandas To Read CSV File.

  1. Open a terminal and run the command pip show pandas to see whether the python pandas library has been installed or not.
    $ pip show pandas
    Name: pandas
    Version: 1.2.3
    Summary: Powerful data structures for data analysis, time series, and statistics
    Home-page: https://pandas.pydata.org
    Author: None
    Author-email: None
    License: BSD
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: numpy, pytz, python-dateutil
    Required-by:
  2. If the python pandas library has not been installed, you can run the command pip install pandas to install it.
    $ pip install pandas
  3. Below is the CSV file content, the file path is /Users/songzhao/employee_info.csv.
    Name,Hire Date,Salary
    jerry,2010-01-01,16000
    tom,2011-08-19,6000
    kevin,2009-02-08,13000
    richard,2012-03-19,5000
    jackie,2015-06-08,28000
    steven,2008-02-01,36000
    jack,2006-09-19,8000
    gary,2018-01-16,19000
    john,2017-10-01,16600
  4. Below is the python source code that can read out the CSV file content data with the python pandas module.
    >>> import pandas as pd
    >>> 
    >>> import os
    >>> 
    >>> cwd = os.getcwd()
    >>> 
    >>> print(cwd)
    /Users/songzhao
    >>> 
    >>> csv_file_path = cwd + '/employee_info.csv'
    >>> 
    >>> csv_file_data = pd.read_csv(csv_file_path)
    >>> 
    >>> print(csv_file_data)
          Name   Hire Date  Salary
    0    jerry  2010-01-01   16000
    1      tom  2011-08-19    6000
    2    kevin  2009-02-08   13000
    3  richard  2012-03-19    5000
    4   jackie  2015-06-08   28000
    5   steven  2008-02-01   36000
    6     jack  2006-09-19    8000
    7     gary  2018-01-16   19000
    8     john  2017-10-01   16600
    >>>
    >>> csv_file_data = pd.read_csv(csv_file_path, sep=",")
    >>> 
    >>> print(csv_file_data)
          Name   Hire Date  Salary
    0    jerry  2010-01-01   16000
    1      tom  2011-08-19    6000
    2    kevin  2009-02-08   13000
    3  richard  2012-03-19    5000
    4   jackie  2015-06-08   28000
    5   steven  2008-02-01   36000
    6     jack  2006-09-19    8000
    7     gary  2018-01-16   19000
    8     john  2017-10-01   16600
    >>> 
    

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.