简体   繁体   中英

compare lines in a file with a string

I'm trying to see if my list already has a specific user in it. I should get "match found" printed out but I don't. I thought the problem was in my php-file so i created a text file with the same contents but it still doesn't find the match.

import urllib2
server = "10.20.68.235"
var = "patrik"
file = urllib2.urlopen("http://"+server+"/list-text.php")

for line in file:
        if line == var:
                print "match found"
        print line,

print "done"

Here is the output im getting:

someguy
user
patrik
juniper
ftpsecure
momeunier
done  

If you create the following file xx.in :

test line 1
test line 2

and run the following Python program, you'll see exactly why the match is failing:

file = open('xx.in')
for line in file:
    print '[%s]' % (line)

The output is:

[test line 1
]
[test line 2
]

showing that the newline characters are being left on the line when they're read in. If you want them stripped off, you can use:

line = line.rstrip('\n')

This will remove all newline characters from the end of the string and, unlike strip() , will not affect any other whitespace characters at either the start or end.

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