How can I read only the header column of a CSV file using Python?

后端 未结 9 729
生来不讨喜
生来不讨喜 2020-12-14 10:05

I am looking for a a way to read just the header row of a large number of large CSV files.

Using Pandas, I have this method available, for each csv file:

         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 10:30

    I might be a little late to the party but here's one way to do it using just the Python standard library. When dealing with text data, I prefer to use Python 3 because unicode. So this is very close to your original suggestion except I'm only reading in one row rather than the whole file.

    import csv    
    
    with open(fpath, 'r') as infile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames
    

    Hopefully that helps!

提交回复
热议问题