2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

2

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
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • 2
    `random.sample` would be a more direct way to get a specific number of randomly chosen items. – Blckknght Jul 17 '13 at 19:59
  • 1
    In general, it is much easier to use a `for` loop to loop over the lines of a file. Ryan's answer uses a list comprehension which contains a `for` loop, but you can also write it as `for line in file:` just like you would for other `for` loops. Just for reference. – 2rs2ts Jul 17 '13 at 21:02
1

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

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • i added this line on the code and it runs, but the results are not what i was expecting... the result i'm looking for is something like this: to read in the text file and sort only a random part of the values and add then to a list. the result i got is only the strings that are "pure numbers" (whithout whitespaces or "\n" for example) – Matheus Corrêa Jul 17 '13 at 18:07