I have the following line of code that opens a document called document.txt that looks somewhat like this.

3 4 5 6 6

3 2 8 9

4 6

with open('document.txt','r') as f:
        for line in f:
                farray = [int(i) for i in line.split(" ")]
                lArray.append(farray)

but I'm getting the following error.

ValueError: invalid literal for int() with base 10: ''

is there something obvious here that I'm missing?

3 Answers

6
Jon Kiparsky On Best Solutions

I'm guessing that there's a blank line at the end of the file. This, when stripped, becomes an empty string, which cannot be parsed as an int.

Deleting the blank line will make this work, but you can think of this as an exercise in defensive programming. As one of my favorite professors once told me, "a good programmer is someone who looks both ways before crossing a one-way street".

0
rcw On

You might have to replace the line skip which is something like this in python

\n

If I were you my code would be:

f = open('document.txt','r')
temp = f.readlines()
array = []
for i in temp:
    i = i.replace("\n","")
    i = i.split(" ")
    for x in range(len(i)):
        i[x] = int(i)
    array.append(i)
0
Mickey Mouse On

I have also gone through this problem. The simple thing you can do is either use strip() method or replace() method.

Hope this will help you to find the answer.