使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:10:29  来源:igfitidea点击:

Check if a string is in a file with Python

pythonfileif-statement

提问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 Pythondelightful?

是不是Python赏心悦目?

回答by camden

This is the top answer from a very similar question.

这是来自一个非常相似的问题的最佳答案

if 'blabla' in open('example.txt').read():
    print "true"