Python Forum

Full Version: Python script Server list - if condition error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Sure, below are the details/algorithm. Please review and advise if I have make any changes to the code.

1. File /root/pydev/serv has server1, server2, server3
cat /root/pydev/serv
server1
server2
server3

2. Expected script function and output
- read the file /root/pydev/serv for its content.
- check the condition, which is "if the serv == server2"
- if the condition matches or equals the contents/line/server from the file then print only that server exclusively. (Example: serv ==server2 then print only "server2" as output.
- if the condition does not matches or equals (example: if condition serv == server5) then only print "No Serv found" in the output.
if I get you right, because you virtually repeat the same thing again

lookup_server = 'server2'
lookup_file = "/root/pydev/serv"

# option1 
with open(lookup_file, "r") as f:
    servers =  [line.strip() for line in f] 
    if lookup_server in servers:
        print(f'{lookup_server} found in file')
    else:
        print(f'{lookup_server} not found in file')
        

#option2
with open(lookup_file, "r") as f:
    for server in f:
        if server.strip() == lookup_server:
            print(f'{lookup_server} found in file')
            break
    else:
        print(f'{lookup_server} not found in file')
Buran - Thanks again. I have executed the code and the output returned as expected..that's exactly I was looking for. Hope you have wonderful day. Can you please suggest good books or resources for Python so that I can bring myself up to speed in Python.
Pages: 1 2