【问题标题】:Check if a string is in a file with Python [duplicate]使用Python检查字符串是否在文件中[重复]
【发布时间】:2018-12-21 19:19:15
【问题描述】:

我是 Python 新手,我正在尝试弄清楚如何在文件中搜索字符串并将其用作 if 子句中的条件: 如果文件中有“String”,则 Print("Blablabla")

【问题讨论】:

    标签: python file if-statement


    【解决方案1】:

    正如您自己所说,只需打开文件并检查它是否在其中。

    with open('myfile.txt') as myfile:
         if 'String' in myfile.read():
             print('Blahblah')
    

    Python 不是很讨喜吗?

    【讨论】:

    • 如果我没记错的话,我们可以使用 "open('myfile.txt', 'r')" 来只读取文件,避免前面的 ".read()" .
    • 可以忽略大小写吗?
    • @Ferdossi 只需在 myfile.read().lower() 中执行 'String'.lower()
    【解决方案2】:

    这是来自very similar question.的最佳答案

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

    【讨论】:

    • 这不会让文件流保持打开状态吗?
    • 这个方法对我不起作用:(
    • @SrgSprinkles 我猜它不起作用,因为这个答案是 Python 2,第一个答案是 Python 3。你必须调用正确的二进制文件。 print"" 和 print() 在版本之间不可互换
    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2016-02-29
    • 2018-10-17
    • 2023-03-31
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多