Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 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 reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...