w3resource

Python: Read the current line from a given CSV file

Python module: Exercise-4 with Solution

Write a Python program to read the current line from a given CSV file. Use csv.reader

open(file) function open the "employees.csv" with file as the "f". Call csv.reader(f) to generate an object which will iterate over each line in the given "employees.csv" file. Pass in the reader object to next(csv_reader) to get a single line from the .csv file.

Sample Solution:

Python Code:

import csv
f = open("employees.csv", newline='')
csv_reader = csv.reader(f)
print(next(csv_reader))
print(next(csv_reader))
print(next(csv_reader))

Sample Output:

['employ_id', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job_id', 'salary', 'commission_pct', 'manager_id', 'department_id']
['100', 'Steven', 'King', 'SKING', '515.123.4567', '1987-06-17', 'AD_PRES', '24000', '', '', '90']
['101', 'Neena', 'Kochhar', 'NKOCHHAR', '515.123.4568', '1987-06-18', 'AD_VP', '17000', '', '100', '90']

Flowchart:

Flowchart: Read the current line from a given CSV file.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to parse a given CSV string and get the list of lists of string values.
Next: Write a Python program to skip the headers of a given CSV file.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Dictionary comprehension:

>>> m = {x: x ** 2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}