读取文本文件中的特定行或字符,不识别文本



veriftype可以工作,但veriftype2不行。是因为我读第二行的方法不准确吗?它正在读取的文本文件每行有一个字符,每个字符上有一个x或一个o。我试着只使用f.read(2),但似乎两者都不奏效。我似乎找不到任何其他问题的来源,因为当我打印应该是行值的变量时,它给了我正确的值,但是if语句没有运行,它只是跳到else部分。

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)

您的代码可以工作,但它无法识别字符,因为readlines()还包含一个换行符,所以它读取'xn'而不是'x'。因此没有字面上的匹配。用.read().splitlines()代替.readlines()来解决这个问题。

最新更新