Gle*_*yak 11 python if-statement file
我是Python的新手,我试图找出如何在文件中搜索字符串并将其用作if子句中的条件:如果文件中有"String",则打印("Blablabla")
hsp*_*her 27
正如你自己所说,只需打开文件并检查它是否在其中.
with open('myfile.txt') as myfile:
if 'String' in myfile.read():
print('Blahblah')
Run Code Online (Sandbox Code Playgroud)
不Python愉快吗?
这是一个非常相似的问题的最佳答案。
if 'blabla' in open('example.txt').read():
print "true"
Run Code Online (Sandbox Code Playgroud)