使用 Python 检查字符串是否在文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32749350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string is in a file with Python
提问by Gleyak
I'm new to Python and I'm trying to figure out how I can search for a string in a file and use it as a condition in a if clause: If "String" is in the file, Print("Blablabla")
我是 Python 新手,我试图弄清楚如何在文件中搜索字符串并将其用作 if 子句中的条件:如果“字符串”在文件中,则 Print("Blablabla")
采纳答案by hspandher
As you yourself said, just open the file and check if it is in it.
正如您自己所说,只需打开文件并检查它是否在其中。
with open('myfile.txt') as myfile:
if 'String' in myfile.read():
print('Blahblah')
Isn't Python
delightful?
是不是Python
赏心悦目?
回答by camden
This is the top answer from a very similar question.
if 'blabla' in open('example.txt').read():
print "true"