Nearby lessons
94 of 159Python - CSV Files
- Understand the CSV (Comma Separated Values) file format
- Import the csv module
- Write records to a CSV file using csv.writer() and writerow()
- Read records from a CSV file using csv.reader()
- Use newline='' to prevent blank lines in CSV files
Introduction to CSV Files
CSV stands for Comma Separated Values.
A CSV file is used to store tabular data such as:
- Student records
- Employee records
- Sales reports
- Product information
Each row in a CSV file represents one record, and each value is separated by a comma.
The csv Module
Python provides the built-in csv module for working with CSV files.
Writing Data into a CSV File
To write data into a CSV file, we use the csv.writer() function to create a writer object.
The writerow() Method
The writerow() method writes a single record into the CSV file.
Example: Write Employee Records
Sample Output
Generated emp.csv File
Explanation
open("emp.csv", "w", newline='')creates the CSV file in write mode. Thenewline=''parameter prevents blank lines from appearing between records.csv.writer(f)creates a CSV writer object that is responsible for writing records into the file.- The first
writerow()call writes the column headings (ENO,ENAME,ESAL,EADDR). - Each subsequent
writerow()call inside the loop writes one employee record.
Importance of newline=''
If we do not use the newline attribute, blank lines will be included between the data rows in the CSV file.
with open("emp.csv", "w", newline='') as f: # no blank lines
with open("emp.csv", "w") as f: # blank lines included
In Python 3, newline='' is required to prevent these blank lines. In Python 2, opening the file in 'wb' mode achieves the same result.
Reading Data from a CSV File
Python provides the csv.reader() function to read data from a CSV file.
The reader() function reads one record at a time and returns each record as a list.
Example: Reading Employee Records
Sample Output
Explanation
csv.reader(f) creates a reader object from the file.
The for record in r loop reads each row of the CSV file. Every record is returned as a list of values.
The first record is the header row, followed by one list for each employee.
- CSV stands for Comma Separated Values and stores tabular data
- csv.writer() creates a writer object that writes records to a CSV file
- writerow() writes one record at a time
- csv.reader() reads each record and returns it as a list
- Opening a CSV file for writing with newline='' prevents blank lines between records