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:

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 Programming skills with w3resource's quiz.
Python: Tips of the Day
Inverts a dictionary with non-unique hashable values:
Example:
def tips_collect_dictionary(obj): inv_obj = {} for key, value in obj.items(): inv_obj.setdefault(value, list()).append(key) return inv_obj ages = { "Owen": 25, "Jhon": 25, "Pepe": 15, } print(tips_collect_dictionary(ages))
Output:
{25: ['Owen', 'Jhon'], 15: ['Pepe']}
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook