How to ignore the first line of data when processing CSV data?

前端 未结 17 2147
庸人自扰
庸人自扰 2020-11-22 10:05

I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don\'t want Python to take the top row into account. Ho

17条回答
  •  悲&欢浪女
    2020-11-22 10:36

    The documentation for the Python 3 CSV module provides this example:

    with open('example.csv', newline='') as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024))
        csvfile.seek(0)
        reader = csv.reader(csvfile, dialect)
        # ... process CSV file contents here ...
    

    The Sniffer will try to auto-detect many things about the CSV file. You need to explicitly call its has_header() method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:

    if sniffer.has_header():
        for header_row in reader:
            break
    for data_row in reader:
        # do something with the row
    

提交回复
热议问题