Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using readlines in python? First time

I have a text file with columns of data and I need to turn these columns into individual lists or arrays. This is what I have so far

f = open('data.txt', 'r')
temp = []
for row in f.readlines():
    Data = row.split()
    temp.append(float(Data[0]))

When I run this I get IndexError: list index out of range.

Snippet of the data below:

16  0.2000  
17  0.3000  
18  0.4000  
20  0.5000  
21  0.6000  
22  0.7000
24  0.8000  
25  0.9000
26  1.000   

I need the first column, if possible to look like this: Data = [16, 17, 18, 20, 21, 22, 24, 25, 26]

like image 208
user1762768 Avatar asked Oct 21 '12 08:10

user1762768


2 Answers

You are getting an empty list Data=[] if you read an empty row. You try to get the first element from the list using Data[0],but because it's an empty list it doesn't have an element 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 print out the Data if IndexError occours - you can see 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 the file, that automatically closes the file after being processed. Also you can loop over 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 are better of using 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']
like image 95
root Avatar answered Oct 13 '22 12:10

root


use with for filehandlers.

with open('path/to/file', 'r') as f:
    for line in f:
        # code.

you index error comes from trying to access Data at the [0] location. which simply means your line was empty.

you should run a quick check before parsing the line...

if len(Data):
    #code
else:
    #empty line?
like image 24
Inbar Rose Avatar answered Oct 13 '22 13:10

Inbar Rose