简体   繁体   English

Python readlines字符串问题

[英]Python readlines string issue

import os
fname = "input1.txt"

if os.path.isfile(fname):
        f = open("input1.txt", "r")

    for row in f.readlines():
            if "logging failed" in row:
                    print "the file does say 'logging failed' in it"
            else:
                    print "the file doesn\'t say 'logging failed' in it"

My input1.txt says logging failedtest so how can i make it notice the "test" so that it should only printout logging failed if the text doesnt have any additional characters? 我的input1.txt记录日志失败测试,​​所以我如何使它注意到“测试”,以便如果文本没有任何其他字符,它应该仅打印记录日志失败?

EDIT: sorry for bad english, what I meant is: If input1.txt has only "logging failed", then it should print out 'file does say it'. 编辑:对不起,英语不好,我的意思是:如果input1.txt只有“记录失败”,那么它应该打印出“文件确实说了”。 If it has any other characters (for example 'logging faaaailed' or 'logging failed1', then it should print out that 'it doesnt say logging failed'. Now it just reads that there is logging failed and ignores any other characters in the input1.txt 如果它还有其他字符(例如'logging faaaailed'或'logging failed1'),则它应该打印出“它不说logging failed”。现在它只是读取到logging失败,而忽略了input1中的任何其他字符。 。文本

Maybe I'm missing something, but why can't you explicitly compare row to the string "logging failed" ? 也许我缺少了一些东西,但是为什么您不能显式比较row与字符串“ logging failed”呢?

eg. 例如。 if row == "logging failed"

您可以尝试以下操作:

if row.find('logging') != -1 and row.endswith('failedtest'):

Try this row.count("logging failed") > 0 尝试此row.count("logging failed") > 0

import os
fname = "input1.txt"

if os.path.isfile(fname):
        f = open("input1.txt", "r")

    for row in f.readlines():
            if row.count("logging failed") > 0:
                    print "the file does say 'logging failed' in it"
            else:
                    print "the file doesn\'t say 'logging failed' in it"

Sample test: 样品测试:

In [4]: t = "the file does say 'logging failed' in it"

In [5]: t.count('logging failed')
Out[5]: 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM