125

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])
Jonas
  • 121,568
  • 97
  • 310
  • 388
andrebruton
  • 2,268
  • 4
  • 29
  • 36

9 Answers9

170

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 2
    What happens if you want to just read the first line rather than iterating? This approach moves the iterator to the next line and you'll lose the value if you want to iterate over the whole list again later. – Mahsan Nourani Jun 08 '21 at 15:29
  • 3
    @MahsanNourani The file pointer can be moved to anywhere in the file, `file.seek(0)` will move it back to the start for example and then you can re-read from start. You'll have to keep the file open obviously to perform seek operation. In general, the point of using iterators is that you'll get one item a time, hence saving memory, if you need multiple iteration on the same data, list is a better datastructure. – Ashwini Chaudhary Jun 09 '21 at 05:23
  • I was just trying to print the first line of the file before doing anything with the data hence my question! This solution is great, I didn't know that. Thanks :) – Mahsan Nourani Jun 10 '21 at 01:11
46

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)
dm03514
  • 54,664
  • 18
  • 108
  • 145
  • 2
    Probably, it is good to add "with open('csv_file', 'r')" as f: csv_reader = csv.reader(f) ..." – Sanchit May 15 '19 at 10:45
30

You can use Pandas library to read the first few lines from the huge dataset.

import pandas as pd

data = pd.read_csv("names.csv", nrows=1)

You can mention the number of lines to be read in the nrows parameter.

josliber
  • 43,891
  • 12
  • 98
  • 133
Aravind Krishnakumar
  • 2,727
  • 1
  • 28
  • 25
19

Just for reference, a for loop can be used after getting the first row to get the rest of the file:

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)  # gets the first line
    for row in reader:
        print(row)       # prints rows 2 and onward
Emerson Peters
  • 373
  • 2
  • 9
16

From the Python documentation:

And while the module doesn’t directly support parsing strings, it can easily be done:

import csv
for row in csv.reader(['one,two,three']):
    print row

Just drop your string data into a singleton list.

Luke
  • 1,369
  • 1
  • 13
  • 37
Robert Elwell
  • 6,598
  • 1
  • 28
  • 32
8

The simple way to get any row in csv file

import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
    csvFileArray.append(row)
print(csvFileArray[0])
Oscar.Chou
  • 81
  • 1
  • 3
6

To print a range of line, in this case from line 4 to 7

import csv

with open('california_housing_test.csv') as csv_file:
    data = csv.reader(csv_file)
    for row in list(data)[4:7]:
        print(row)
Biplob Das
  • 2,818
  • 21
  • 13
  • I only got this to work by using `with open('C:\\Users\\username\\Desktop\\csv_file.csv', encoding='utf-8') as csv_file:` as the first line – jeppoo1 Apr 07 '21 at 08:56
1

I think the simplest way is the best way, and in this case (and in most others) is one without using external libraries (pandas) or modules (csv). So, here is the simple answer.

""" no need to give any mode, keep it simple """
with open('some.csv') as f:
    """ store in a variable to be used later """
    my_line = f.nextline()
    """ do what you like with 'my_line' now """
-1

For Python3 use: my_line = next(f)