Nearby lessons

94 of 159

Python - CSV Files

📌 What You Will Learn
  • 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.

🐍Code Cell
1import csv
Output
No output captured.

Writing Data into a CSV File

To write data into a CSV file, we use the csv.writer() function to create a writer object.

🐍Code Cell
1writer = csv.writer(file)
Output
No output captured.

The writerow() Method

The writerow() method writes a single record into the CSV file.

🐍Code Cell
1writer.writerow(row_data)
Output
No output captured.

Example: Write Employee Records

🐍Code Cell
1import csv
2 
3f = open("emp.csv", "w", newline='')
4 
5w = csv.writer(f)
6 
7w.writerow(["ENO", "ENAME", "ESAL", "EADDR"])
8 
9n = int(input("Enter Number of Employees: "))
10 
11for i in range(n):
12 
13 eno = input("Employee Number: ")
14 ename = input("Employee Name: ")
15 esal = input("Employee Salary: ")
16 eaddr = input("Employee Address: ")
17 
18 w.writerow([eno, ename, esal, eaddr])
19 
20print("Employee Data Written Successfully")
21 
22f.close()
Output
No output captured.

Sample Output

Generated emp.csv File

Explanation

  • open("emp.csv", "w", newline='') creates the CSV file in write mode. The newline='' 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.

🐍Code Cell
1import csv
2 
3reader = csv.reader(file)
Output
No output captured.

Example: Reading Employee Records

🐍Code Cell
1import csv
2 
3f = open("emp.csv", "r")
4 
5r = csv.reader(f)
6 
7for record in r:
8 print(record)
9 
10f.close()
Output
No output captured.

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.

📝 Key Takeaways
  • 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

🧠 Test Your Knowledge

7 Questions
Progress: 0 / 7