0

Below is the code to compare line two of the file with the input. This only works if there is nothing else in the file, how would I change the code so it still works when the file has many lines of text in.

name = input("Enter name: ")
with open("numbers") as f:
    lines = f.readlines() # a list of all the lines
    if lines[1] == name: # the second line (0 indexing)
user888469
  • 137
  • 2
  • 8
  • do a for loop that loops through all of the lines list and compares them to the input – Hunter Oct 15 '17 at 18:23
  • 1
    The problem is the newline character at the end of the line. You have to remove that before you compare it to the name. – Aran-Fey Oct 15 '17 at 18:26
  • Possible duplicate of [Best method for reading newline delimited files in Python and discarding the newlines?](https://stackoverflow.com/questions/544921/best-method-for-reading-newline-delimited-files-in-python-and-discarding-the-new) – Aran-Fey Oct 15 '17 at 18:26
  • @Rawing gave the solution in comments. There u go – Davo Oct 15 '17 at 18:31

2 Answers2

0

You wrote if lines[1] == name: foo(). To apply this to all lines, use:

    lines = f.readlines()
    for line in lines:
        if line.rstrip() == name:
            foo()

The rstrip() removes whitespace at the end, like newlines.

More compactly, if you're processing every line and don't need indexing, you could iterate over the file rather than over the list returned by readlines:

with open("numbers") as f:
    for line in f:
        if line.rstrip() == name:
            foo()
J_H
  • 17,926
  • 4
  • 24
  • 44
0

When your file has only 2 lines, the 2nd line will be what you expected, so your program works.

When you have more than 2 lines, the 2nd line ends with a new line character \n. Just make sure to get rid of the last character before you compare.

if lines[1].rstrip("\n") == name: will do.

Thanks to @Rawing

Davo
  • 526
  • 3
  • 19