You get an empty list Data=[] if you read an empty line. You are trying to get the first item from a list using Data[0] , but since it is an empty list, it does not have an item at position 0, so you get an IndexError .
Data=''.split() Data[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-686-0792b03cbbdf> in <module>() ----> 1 Data[0] IndexError: list index out of range
This will output the text Data if IndexError occours - you will see for yourself that it prints an empty list:
f=open('file','r') temp = [] for row in f.readlines(): Data = row.split() try: temp.append(float(Data[0])) except IndexError: print Data
You can use the with statement to open a file that automatically closes the file after processing. You can also scroll the file itself without using readlines() .
with open(file,'r') as f: for row in f: Data = row.split() try: print Data[0] except IndexError: print 'You have an empty row'
EDIT: you better use the csv module:
import csv with open('file.csv', 'rb') as f: reader = csv.reader(f, delimiter=' ') print [row[0] for row in reader if len(row)] >>> ['16', '17', '18', '20', '21', '22', '24', '25', '26']
root
source share