Matheus Corrêa
Matheus Corrêa

Reputation: 21

Value Error : invalid literal for int() with base 10: ''

I'm new in Python and I don't know why I'm getting this error sometimes.

This is the code:

import random
sorteio = []
urna = open("urna.txt")

y = 1
while y <= 50:
    sort = int(random.random() * 392)
    print sort
    while sort > 0:
        x = urna.readline()
        sort = sort - 1
    print x  
    sorteio = sorteio + [int(x)]
    y = y + 1
print sorteio

Where urna.txt is a file on this format:

1156
459
277
166
638
885
482
879
33
559

I'll be grateful if anyone knows why this error appears and how to fix it.

Upvotes: 2

Views: 1347

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123550

.readline() returns an empty string when you come to the end of the file, and that is not a valid number.

Test for it:

if x.strip():  # not empty apart from whitespace
    sorteio = sorteio + [int(x)]

You appear to beappending to a list; lists have a method for that:

sorteio.append(int(x))

If you want to get a random sample from your file, there are better methods. One is to read all values, then use random.sample(), or you can pick values as you read the file line by line all the while adjusting the likelihood the next line is part of the sample. See a previous answer of mine for a more in-depth discussion on that subject.

Upvotes: 1

Ryan Haining
Ryan Haining

Reputation: 36882

Upon attempting to read past the end of the file, you're getting an empty string '' which cannot be converted to an int.

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

to satisfy the requirement of selecting 50 random lines from the text value, if I understand your problem correctly:

import random

with open("urna.txt") as urna:
    sorteio = [int(line) for line in urna] # all lines of the file as ints

selection = random.sample(sorteio, 50)

print selection

Upvotes: 2

Related Questions