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

后端 未结 7 1319
终归单人心
终归单人心 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:32

    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
    
    0 讨论(0)
  • 2020-11-28 05:35

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 05:38

    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)
    
    0 讨论(0)
  • 2020-11-28 05:45

    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])
    
    0 讨论(0)
  • 2020-11-28 05:52

    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.

    0 讨论(0)
提交回复
热议问题