简体   繁体   中英

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?

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'. 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

Maybe I'm missing something, but why can't you explicitly compare row to the string "logging failed" ?

eg. if row == "logging failed"

您可以尝试以下操作:

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

Try this 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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