Q:

Test if string exists in file with Python

I'd like to add only servers currently doesn't exist at file
My current code :
 f = open(filename,'a')
 for server in cmo.getServers() :
    print >>f, server.getListenAddress()

Thanks in advance

A:

try this:
data = set( [i.strip() for i in open( filename, 'r' ).readlines()] )

for server in cmo.getServers() :
    data.add( server.getListenAddress() )

open( filename, 'w' ).write('\n'.join(data))

