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

后端 未结 2 846
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2021-01-26 00:45

    Since all you want to do is write the file in reverse order, just write the same row back, but in reverse; like this:

     writer.writerow(row[::-1])
    

    A negative index starts from the right, and a negative step value (the third argument in the slice syntax) will simply reverse the object.

    This will stop the error you are seeing now, and in case you have rows columns that are not 2, they will also be written in reverse.

    0 讨论(0)
提交回复
热议问题