0
file = open("text.txt", "r")
needed = ["Name", "Class", "Level"]
gotten = []
y = []
x = False

for need in needed:
    print("The bois are back in town")
    for line in file:
        for character in line:
            y.append(character)
        y.remove("\n")
        line = ''.join(y)
        y.clear()
        if x == True:
            gotten.append(line)
            x = False
        if line == need:
            x = True
        print(line)
        print(x)
print(gotten)

and text.txt looks like this:

Name
Mano
Class
Fighter
Level
18

Whenever I run this set of code, it returns the following:

The bois are back in town
Name
False
Mano
False
Class
True
Fighter
False
Level
False
18
False
The bois are back in town
The bois are back in town
['Mano']

Basically, I use "The bois are back in town" as a reminder to me to denote when the outermost For loop iterates. The output is as expected the first time through; it prints each line, and whether or not the contents (haven removed the \n) or equal to need of the outer For loop. However, when it iterates the second and third time, it only prints "The bois are back in town", but not the following printing lines like it did the first iteration. Why?

  • Boys not bois. Use the debugger to go through your code and see what's happening. Use spyder IDE if you are not using a IDE – Tarik Dec 05 '20 at 02:35
  • First, you can only read a file once, so save off the lines with with something like `lines = file.readlines()` and then update your for loop to be `for line in lines:`. Next, use `line = line.strip("\n")` instead of reading the line character-by-character and then trying to remove the `\n`, which may not actually exist and will raise an error. – dstricks Dec 05 '20 at 02:54

0 Answers0