117

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])
1
  • what is the structure of your csv? What is row when you are iterating through reader?
    – dm03514
    Jun 23, 2013 at 15:27

8 Answers 8

164

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
3
  • 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. Jun 8, 2021 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. Jun 9, 2021 at 5: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 :) Jun 10, 2021 at 1:11
45

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)
1
  • 2
    Probably, it is good to add "with open('csv_file', 'r')" as f: csv_reader = csv.reader(f) ..."
    – Sanchit
    May 15, 2019 at 10:45
28

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.

16

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
15

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.

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])
3
  • 3
    To make this work in python3, just remove the 'b' in 'rb' Jan 13, 2018 at 22:57
  • 1
    This just works, actually without the delimiter='.'.
    – suvtfopw
    Jan 24, 2019 at 7:05
  • 1
    To answer the posters question, just add a break after the csvFileArray.append(row) and it will only read the first line. Sep 17, 2019 at 2:48
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)
1
  • 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 7, 2021 at 8:56
0

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 """

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.