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")
所以,我想要它做的是打印"""曾经,作为"""出现在我的文件中一次。为什么不这样做?
答案 0 :(得分:1)
if "the" in "newfile.txt":
print("the")
这里的if语句验证字符串文字“the”是否在另一个字符串文字“newfile.txt”中,并且显然是假的,因此不会打印任何内容。
为了您的目的和更多pythonic文件操作,请考虑使用 with 语句,如下例所示:
#!/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
答案 1 :(得分:0)
不是"the" in "Newfile.txt"
,而是"the" in lines[i]
。
答案 2 :(得分:0)
if "the" in "newfile.txt":
print("the")
您正在验证字符串"the"
中是否存在子字符串newfile.txt
。
将if "the" in file:
用于整个文件
或者,if "the" in lines[i]:
,仅用于该行
答案 3 :(得分:0)
这一行错了:
if "the" in "newfile.txt":
它试图找到""" in" newfile.txt"字符串,不在文件中。您可能希望在该行中找到它,因此请按以下方式进行修复:
if "the" in lines[i]:
它比较所有的行和打印"""什么时候找到它。