简体   繁体   中英

Read a specific line or character from a text file, not recognizing the text

veriftype works, but veriftype2 doesn't. Is it because my method to read the second line isn't accurate? The text file it's reading from has one character on each line, either an x or an o on each. I tried using just f.read(2) but it seems like neither one does the trick. I can't seem to find any other source of problem, since when I print the variable that should be the value of the line, it gives me the correct value, but the if statement doesn't run, and it just skips to the else part.

def veriftype(self):
    f = open("Transfert.txt", "r")
    y = f.readline(1)
    print (y)
    if y == "x":
        if type(self) == Retriever or type(self) == Shepherd:
            self.points += 1
            print("It worked for the dogs.")
        else:
            print("It recognized the type wasn't correct, so it didn't get any points.")
    elif y == "o":
        print("It recognized the o")
    else:
        print("It didn't recognize anything")
    print(self.points)


def veriftype2(self):
    with open("Transfert.txt") as f:
        ligne = f.readlines()
    z = ligne[2]
    print(z)
    if ligne[2] == "x":
        if type(self) == Perroquet or type(self) == Macaw:
            self.points += 1
            print("It worked for the birds.")
        else:
            print("It recognized the type wasn't correct, so it didn't get any points.")
    elif ligne[2] == "o":
        print("It recognized the o")
    else:
        print("It didn't recognize anything")
    # print(self.points)

Your code works, but it cannot recognize the characters because readlines() also includes a newline character, so it reads 'x\n' rather than 'x'. Therefore there is no literal match. Replace .readlines() with .read().splitlines() to solve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM