1

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?

2
  • Try check out if you have a blank string, this can be the reason of your exception Commented Apr 19, 2017 at 2:44
  • To debug, add print(line.split(" ")) before the crash. Commented Apr 19, 2017 at 2:59

3 Answers 3

8

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Yes! That was the issue. Thanks tons!
Glad I could help!
1

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)

1 Comment

In general, the python style is to iterate over the objects in a list directly, not via their index. "For each item in the list, do something to the item" is preferable to "For each number i in the list of numbers from zero to the count of items in the list, look up the item indexed by i and do something to that number".
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.