Python:读取模式。加载到列表(使用 for 循环)并在单独的代码块中使用 read() 方法

标签 python file text loading

我正在测试此代码的多个场景,并想了解 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/

相关文章:

python - 提高数组操作的性能

用于绘制函数图形的 Python 模块

php - 文件上传不工作 | PHP

c - 获取文本而不是 EOF

python覆盖上一行

perl - 我应该保持文件打开还是应该经常打开和关闭?

Java:将所有路径移动到单独的文件

javascript - 无法将文本转换为 JavaScript 数组

java - 如何在 JavaFX 中通过 CSS 对文本获得浮雕(凸起的字母)效果?

python - psycopg2安装成功,但无法导入python