1

I have been practising reading files in Python, as I am new to that particular area.

I have a text file like:

Hello,my,name,is,Jack

and I want to transfer that to a list like this:

["Hello", "my", "name", "is", "Jack"]

I tried doing this:

array = []
file = open("Names.txt", "r")
for line in file:
    array.append(line.split(","))
print(array)

but I got a really bizarre error:

File "C:\Python27\lib\random.py", line 261, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is
empty
IndexError: list index out of range
>>>

How do I fix it?

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 2
    The code here doesn't seem to be where the error is. Do you call `random.choice` at any point in your code? – Patrick Haugh Oct 31 '17 at 18:13
  • 2
    This error looks like it comes from elsewhere in your code. – Erick Shepherd Oct 31 '17 at 18:13
  • It may be with how you are declaring the random int. Do you declare seq yourself? – OmegaNalphA Oct 31 '17 at 18:16
  • @PatrickHaugh no I didn't, the error is coming from the python library itslef it seem "C:\Python27\lib\random.py", line 261. Don't really know why, I haven't even touched it. –  Oct 31 '17 at 18:19
  • Possible duplicate of: https://stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python – Vasilis G. Oct 31 '17 at 18:21
  • @VasilisG.not a possible duplicate as my error is completely different –  Oct 31 '17 at 18:31
  • Is there any more to the stacktrace...like what `random` module function was called from where? – martineau Oct 31 '17 at 18:45

1 Answers1

-1

You have not posted your full code (as in this code, you haven't used the random module), but it can be seen from the error that you are trying to do random.choice on an empty list.

You can reproduce the error like so:

>>> import random
>>> random.choice([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/random.py", line 275, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

So if you post the whole code, we can help you further, but otherwise you need to locate where you are calling random.choice() and debug what list you are calling it on.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54