Python 我的程序没有';不要为了打印而打印任何东西(“the”)。有人能解释为什么吗?

Python 我的程序没有';不要为了打印而打印任何东西(“the”)。有人能解释为什么吗?,python,Python,所以,我想让它做的是,打印“the”一次,就像“the”在我的文件中出现一次一样。它为什么不这样做呢?不是“Newfile.txt”中的“代码”,而是第[i]行中的“代码” file = open("newfile.txt","w") file.write("Hello World") file.write("This is my text file") file.write("and the day is nice.") file.close() file= open("new

所以,我想让它做的是,打印“the”一次,就像“the”在我的文件中出现一次一样。它为什么不这样做呢?

不是“Newfile.txt”中的“代码”,而是第[i]行中的“代码”

file = open("newfile.txt","w") 

file.write("Hello World") 
file.write("This is my text file") 
file.write("and the day is nice.")  
file.close() 

file= open("newfile.txt")
lines = file.readlines()
for i in range(len(lines)):
    if "the" in "newfile.txt":
        print("the")
您正在验证字符串
newfile.txt
中是否有子字符串“”

使用
如果文件中的“the:
用于整个文件

或者,
如果第[i]:
行中的“the”,则仅该行是错误的:

if "the" in "newfile.txt":
    print("the")
它尝试在“newfile.txt”字符串中查找“the”,而不是在文件中。您可能希望在行中找到它,因此按如下方式修复它:

if "the" in "newfile.txt":
它比较所有的行,找到后打印“the”

if "the" in lines[i]:
这里的if语句验证字符串文字“The”是否在另一个字符串文字“newfile.txt”中,它显然是false,因此不会打印任何内容

为您的目的和更多的Python文件操作,请考虑使用<强> >语句作为以下示例:

if "the" in "newfile.txt":
    print("the")
是“newfile.txt”中的“the”吗?提示:“newfile.txt”中的“the”检查字符串
中的
是否是字符串
newfile.txt的一部分
#!/usr/bin/env python
# -*- coding: utf-8 -*-

filename = 'newfile.txt'
with open(filename, 'w') as f:
    f.write("Hello World\n")
    f.write("This is my text file\n")
    f.write("and the day is nice.\n")

with open(filename) as f:
    for line in f.readlines():
        if 'the' in line:
            print line