1

I'm trying to read info from a file and print it's information. Using a test program, I could get it working like this:

file = open("cooltextfile.txt", "r")
for line in file:
    if "BobRoss" in line:
        print(line)

Using above method, it prints all lines containing "Bob Ross".

However, when I use it in my main program like this, it's not even printing the line if I tell it to print the whole line:

number = 0
index = 0

textFile = open("cooltextfile.txt", "r")
lineInfo = textFile.readlines()

for line in textFile:
    index += 1

    print(line) # - An attempt to print the entire line
                    
    if "BobRoss" in line:
        number += 1

        print(str(number) + ". " + line)
        print("Order: " + lineInfo[index])
                
textFile.close()

Upon further inspection it would seem that the for-loop never starts. Any reason as to what could be causing the loop to not start?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Remfy
  • 61
  • 4

2 Answers2

1

Suggestions:

  1. use enumerate to get the index,
  2. you have to loop through the lines, so use lines = file.readlines() or it will get just a character
  3. use fstrings instead of concatenation, it will be faster
  4. use with open(filename,'r'), instead of fp = open(filename)it will be cleaner and it will close your file at the end automatically.

code reassembled:

with open("cooltextfile.txt",'r') as textFile:
    number,index = 0,0
    lines=textFile.readlines()
    for index,line in enumerate(lines): 
        if "BobRoss" in line:
            number += 1 #incrementing the number of lines that contains BobRoss
            print(f"{number}.{line}") 
            print(f"Order: {index}")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
1

Think of reading a file like playing a tape. You called textFile.readlines(), now you've reached the end of the tape. Now you try to play it again (in a loop), but you're still at the end of the tape. You need to rewind the tape before: textFile.seek(0)