'Python/Pygame Error "TypeError: '_io.TextIOWrapper' object is not subscriptable"

I Made a platformer game with a second file with the level map in it. Now I want to change that it loads the level map from a text document. But I always get the error

TypeError: '_io.TextIOWrapper' object is not subscriptable.

When I print it, I see it read the document, but I still get the error in line 12.

def setup_world(l1,l2,l3,l4,l5,l6,l7,l8,l9):
    global level_map
    i = 0
    on = True
    top = True
    mid = False
    bot = False
    while on:
        if top:
            level_top = l1[i] + l2[i] + l3[i]   # Error Here
            level_map.append(level_top)
            i += 1
            if i == 32:
                i = 0
                top = False
                mid = True
        if mid:
            level_mid = l4[i] + l5[i] + l6[i]
            level_map.append(level_mid)
            i += 1
            if i == 32:
                i = 0
                mid = False
                bot = True
        if bot:
            level_bot = l7[i] + l8[i] + l9[i]
            level_map.append(level_bot)
            i += 1
            if i == 32:
                i = 0
                bot = False
                on = False

level_1 = open('textdatei.txt','r')     #I Tried this
```


Solution 1:[1]

You can't index (__getitem__) a _io.TextIOWrapper object. What you can do is work with a list of lines. Try this in your code:

lst = open(input("Input file name: "), "r").readlines()

Also, you aren't closing the file object, this would be better:

with open(input("Input file name: ", "r") as lst:
    print(medianStrat(lst.readlines()))

with ensures that file get closed, see docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kris