示例测试文件不包含“Open”,但它包含“Items”string。
它的结构就像
Dash
>> Dash (63 Items)
>> Dash1 (31) Items)
现在我想要的是
如果'Open'
string在text
文件中:
条件或打印真实
elif 'Items'
string不在文本文件中:
打印错误就在那里
其他:
什么都不打印是新的
现在根据文本文件,我应该得到什么是新的,但我得到错误是在那里,而"Items" string就在那里文件无法弄清楚为什么它在中间elif短路。
python
f = open(r'''C:\Users\ss\Desktop\Work\test.txt''', 'r')
if 'Open' in f.read():
print("Open")
elif 'Items' not in f.reads():
print("Error")
else:
print("No")
No Error Messages
"I expected the output from this file is Nothing new as in text"以及“打开”是否在文本文件中
"I expect the output to be true"
或者如果文件中没有'Items'string:
"I expect the output to be error"
分析解答
您不能多次使用f.read()
。对于更多
所以,我已经将它分配给data
并多次使用来检查。
试试这个,
with open('yourfile.txt', 'r') as f:
data = f.read()
if 'Open' in data :
print("Open")
elif 'Items' not in data :
print("Error")
else:
print("No")