Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read one single line of csv data in Python?

There is a lot of examples of reading csv data using python, like this one:

import csv with open('some.csv', newline='') as f:   reader = csv.reader(f)   for row in reader:     print(row) 

I only want to read one line of data and enter it into various variables. How do I do that? I've looked everywhere for a working example.

My code only retrieves the value for i, and none of the other values

reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in reader:   i = int(row[0])   a1 = int(row[1])   b1 = int(row[2])   c1 = int(row[2])   x1 = int(row[2])   y1 = int(row[2])   z1 = int(row[2]) 
like image 811
andrebruton Avatar asked Jun 23 '13 15:06

andrebruton


People also ask

How do I extract a row from a CSV file in Python?

Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. Step 2: Create a reader object by passing the above-created file object to the reader function. Step 3: Use for loop on reader object to get each row.

How do I read one column from a CSV file in Python?

Use pandas. read_csv() to read a specific column from a CSV file. To read a CSV file, call pd. read_csv(file_name, usecols=cols_list) with file_name as the name of the CSV file, delimiter as the delimiter, and cols_list as the list of specific columns to read from the CSV file.


1 Answers

To read only the first row of the csv file use next() on the reader object.

with open('some.csv', newline='') as f:   reader = csv.reader(f)   row1 = next(reader)  # gets the first line   # now do something here    # if first row is the header, then you can do one more next() to get the next row:   # row2 = next(f) 

or :

with open('some.csv', newline='') as f:   reader = csv.reader(f)   for row in reader:     # do something here with `row`     break 
like image 132
Ashwini Chaudhary Avatar answered Sep 24 '22 14:09

Ashwini Chaudhary