我正在测试此代码的多个场景,并想了解 Python 以这种方式运行的原因。 两种情况都是相同的代码,但代码块的顺序相反。
#Peach is written in this .txt file
inputFile = open("C:\\...\\filename.txt", 'r')
场景 1:此代码正确打印了列表,但最后打印了 False,即使“Peach”在 .txt 文件中也是如此
#Loading into lists
myList = []
#For each line in the file
for line in inputFile:
#Add the line to myList, stripping out whitespace
myList.append(line.strip())
print(myList)
if "Peach" in inputFile.read():
print("Peach in .txt file?", True)
else:
print("Peach in .txt file?", False)
inputFile.close()
场景 2:相同的代码,不同的位置。正确打印 True 但会打印出一个空列表。
if "Peach" in inputFile.read():
print("Peach in .txt file?", True)
else:
print("Peach in .txt file?", False)
#Loading into lists
myList = []
#For each line in the file
for line in inputFile:
#Add the line to myList, stripping out whitespace
myList.append(line.strip())
print(myList)
inputFile.close()
最佳答案
你可以试试这个方法:
with open("","r") as f:
data=f.read()
if data.find("Peach")>-1:
print("Peach found in .txt file")
else:
print("Peach not found in .txt file")
我们从 .txt
文件中读取文件和写入文本到数据中。我们正在那个数据
中找到“Peach”
。如果找到打印找到否则打印未找到。
或者,如果您想逐行列出,则:
with open("","r") as f:
data=f.readlines()
for dat in data:
if dat.find("Peach")>-1:
print("Peach found in .txt file")
break
else:
print("Peach not found in .txt file")
关于Python:读取模式。加载到列表(使用 for 循环)并在单独的代码块中使用 read() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68425298/