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.
- Import python
csv
module.>>> import csv
- Open the CSV file by specified file path with reading mode.
>>> csv_file = open('csv_user_info.csv','r')
- Create the CSV file reader object by the python
csv
module’sreader
function.>>> csv_reader = csv.reader(csv_file)
- 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'", "'jerry@dev2qa.com'", "'CEO'"] ["'tom'", "'tom@dev2qa.com'", "'Developer'"]
2. How To Write Data To CSV File In Python.
- Import the python
csv
module.>>> import csv
- Open a file for writing CSV data into it.
>>> csv_file = open('test.csv','w')
- Create a CSV file writer object with the python
csv
modulewriter
method.>>> csv_writer = csv.writer(csv_file, delimiter=';')
- Call the csv_writer object’s
writerow
method to write text into it.>>> csv_writer.writerow('I love python')
- 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()
- 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.
- Import the python
csv
module, and open the CSV file by the file path.>>> import csv >>> >>> csv_file = open('csv_user_info.csv','r')
- Create the csv reader object by the python
csv
moduleDictReader
method.>>> csv_reader = csv.DictReader(csv_file)
- 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'", "'jerry@dev2qa.com'"), ("'Title'", "'CEO'")]) OrderedDict([("'Name'", "'tom'"), ("'Email'", "'tom@dev2qa.com'"), ("'Title'", "'Developer'")])
4. How To Write Python Dictionary Object Data Into CSV File.
- 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'} ]
- Create CSV file row headers in a python list.
>>> csv_headers = ['Title', 'Salary']
- Open a file to write CSV data into it.
>>> csv_file = open('test-dict.csv','w')
- Invoke the python
csv
module’sDictWriter
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)
- Write the CSV row headers and python dictionary object to the CSV file.
>>> csv_writer.writeheader() >>> >>> csv_writer.writerows(dict_obj)
- Do not forget to invoke the file object’s
flush
method to save the changes to the CSV file.>>> csv_file.flush()
- Below is the CSV file content.
Title,Salary CEO,10000 Manager,9000
5. How To Use Pandas To Read CSV File.
- 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:
- If the python pandas library has not been installed, you can run the command
pip install pandas
to install it.$ pip install pandas
- 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
- 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 >>>