Reading column names alone in a csv file

前端 未结 9 2255
不思量自难忘°
不思量自难忘° 2020-12-23 18:58

I have a csv file with the following columns:

id,name,age,sex

Followed by a lot of values for the above columns. I am trying to read the column names alone and

相关标签:
9条回答
  • 2020-12-23 19:44

    here is the code to print only the headers or columns of the csv file.

    import csv
    HEADERS = next(csv.reader(open('filepath.csv')))
    print (HEADERS)
    

    Another method with pandas

    import pandas as pd
    HEADERS = list(pd.read_csv('filepath.csv').head(0))
    print (HEADERS)
    
    0 讨论(0)
  • 2020-12-23 19:45

    How about

    with open(csv_input_path + file, 'r') as ft: header = ft.readline() # read only first line; returns string header_list = header.split(',') # returns list;

    I am assuming your input file is CSV format. If using pandas, it takes more time if the file is big size because it loads the entire data as the dataset.

    0 讨论(0)
  • 2020-12-23 19:50
    import pandas as pd
    data = pd.read_csv("data.csv")
    cols = data.columns
    
    0 讨论(0)
提交回复
热议问题