How to check if a CSV has a header using Python?

前端 未结 5 557
再見小時候
再見小時候 2021-01-17 22:54

I have a CSV file and I want to check if the first row has only strings in it (ie a header). I\'m trying to avoid using any extras like pandas etc. I\'m thinking I\'ll use a

5条回答
  •  不思量自难忘°
    2021-01-17 23:46

    Well i faced exactly the same problem with the wrong return of has_header for sniffer.has_header and even made a very simple checker that worked in my case

        has_header = ''.join(next(some_csv_reader)).isalpha()
    

    I knew that it wasn't perfect but it seemed it was working...and why not it was a simple replace and check if the the result was alpha or not...and then i put it on my def and it failed.... :( and then i saw the "light"
    The trouble is not with the has_header the trouble was with my code because i wanted to also check the delimiter before i parse the actual .csv ...but all the sniffing has a "cost" as they advance one line at a time in the csv. !!!
    So in order to have has_header working as it should you should make sure you have reset everything before using it. In my case my method is :

      def _get_data(self, filename):
            sniffer = csv.Sniffer()
            training_data = ''
            with open(filename, 'rt') as csvfile:
                dialect = csv.Sniffer().sniff(csvfile.read(2048))
                training_data = csv.reader(csvfile, delimiter=dialect.delimiter)
                csvfile.seek(0)
                has_header=csv.Sniffer().has_header(csvfile.read(2048))
                #has_header = ''.join(next(training_data)).isalpha()
                csvfile.seek(0)
    

提交回复
热议问题