Heather Lara Heather Lara - 23 days ago 9
Python Question

Can't Find and Output Lines From Text files (PYTHON)

I'm trying to take the user's input and compare it with the contents of a text file. They will enter an eight digit number and if that number is present in the txt file then the code should output the line in which it's present on.

while (len(code) == 8):

with open('GTIN Products.txt', 'r') as search:
for line in search:
line = line.rstrip('\n')
if code == line:
print(line)


When the program is run and the number is entered, there is no output. Just blank.

Answer

Two thoughts:

1) Are you sure you are correctly opening the file and reading the contents?

2) You are asking the 8 character code to be identical to the line, meaning the line must also be 8 characters. Is that the case? You may want to try

if code in line:
    print(line)
    break
Comments