IndexError: list index out of range in CSV file reading python

后端 未结 2 845
情话喂你
情话喂你 2021-01-26 00:35

I have a csv file contaning 30000000 entries. like this

കൃഷി 3
വ്യാപകമാകുന്നു 2
നെല്‍കൃഷി 2
വെള്ളം 2
നെല്ല് 2
മാത്രമേ 2
ജല 2

When I try to reve

2条回答
  •  时光说笑
    2021-01-26 00:44

    You have at least one row that doesn't have 2 columns separated by a tab. An empty line, for example, or if your format doesn't actually use tabs.

    You have two options:

    1. skip rows with fewer columns than you need:

      for row in reader:
          if len(row) < 2:
              continue
          writer.writerow((row[1], row[0]))
      
    2. fix your delimiter to match the actual file content:

      reader = csv.reader(f, delimiter=' ')
      

      you could use the csv.Sniffer() class to try and automate delimiter selection, if you have more than one file to process, and these files are not all following the same CSV dialect.

提交回复
热议问题