Trying to get a random line from a file, getting TypeError
Question: I am working on a python project that needs to read a random line from a text
file so I tried to insert a variable that is a random number into the
lines[].strip() function in python and got the error: `TypeError: 'int' object
has no attribute '__getitem__'` here is the code:

    
    
    rand = random.randrange(0, 10)
    file = open("file.txt", "r")
    line1 = lines[rand].strip()
    


Answer: It looks like you are not reading the file properly and that your `lines`
variable is an integer. Showing us more of your code would help. Getting a
specific line from a file can be done in multiple ways. Here's a few demos:

Either read lines until you are at the line you want:

    
    
    with open('file.txt') as f:
        for num, line in enumerate(f):
            if num == some_number:
                print(line)
                break
    

Or read the whole file, split the lines and access your line by a specific
index. This method is not advised if your files are large and you just need
one line.

    
    
    with open('file.txt') as f:
        data = f.readlines() 
        print(data[some_number])
    

Finally, you can use
[linecache](https://docs.python.org/2/library/linecache.html):

    
    
    import linecache
    line = linecache.getline('file.txt', some_number)
    print(line)       
    

