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

后端 未结 7 1360
终归单人心
终归单人心 2020-11-28 05:04

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)
          


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-28 05:37

    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
    

提交回复
热议问题