Python list index out of range on return value of split

前端 未结 4 662
南笙
南笙 2021-01-18 11:22

I\'m writing a simple script that is trying to extract the first element from the second column of a .txt input file.

import sys

if (len(sys.argv) > 1):         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 11:50

    you probably have empty line(s) after your data, I ran your test code without them it worked as expected.

    $ python t.py t.txt
    file opened
    389182.567
    389182.590
    389182.611
    389182.631
    389182.654
    

    if you don't want to remove them, then simply check for empty lines.

    for line in f:
        if line.strip(): # strip will remove all leading and trailing whitespace such as '\n' or ' ' by default    
            line = line.strip("\n ' '")
            line = line.split(",") 
            print line[1]
    

提交回复
热议问题