Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - 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)
question from:https://stackoverflow.com/questions/65833800/read-a-specific-line-or-character-from-a-text-file-not-recognizing-the-text

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...