Daryll
Daryll

Reputation: 35

Python for loop, prints on multiple lines

To start I'm a network engineer and complete Python noob, I know the basics, i can read bits, but struggle to put it all together.

I've written a very basic for loop script:

    ip_list = open('/home/daryll/scripts/ip_list')
    for ip in ip_list:
        print ("set security address-book global address", ip, ip + "/32")

I'm expecting this back:

set security address-book global address 192.168.10.1 192.168.10.1/32  
set security address-book global address 192.168.10.2 192.168.10.2/32  
set security address-book global address 192.168.10.3 192.168.10.3/32

however i'm getting this:

set security address-book global address 192.168.10.1
 192.168.10.1
/32
set security address-book global address 192.168.10.2
 192.168.10.2
/32
set security address-book global address 192.168.10.3
 192.168.10.3
/32

I'm sure this obvious to you guys but it's not to me and would appreciate a little with my code please

To add to this how do i add multiple different lines, for example

        commands = ( 
    "set interfaces", ip, "family ethernet-switching port-mode trunk"
    "set interfaces", ip, "family ethernet-switching vlan members vlan1"
    "set interfaces", ip, "family ethernet-switching native-vlan-id vlan2"
    )

I won't show the output as it's very messy, but when i do this i get everything all on 1 line how can i get

    set interfaces 192.168.10.1 family ethernet-switching port-mode trunk
    set interfaces 192.168.10.1 family ethernet-switching vlan members vlan1
    set interfaces 192.168.10.1 family ethernet-switching native-vlan-id vlan2

Finally i don't know if this is how i ask this question i tried to start a second question on the back of this but it wouldn't let me.

Thanks

Upvotes: 0

Views: 454

Answers (1)

Vidhan
Vidhan

Reputation: 26

Iterating through lines in a file will leave a new line character (\n) at the end of each line, except for the last one. To remove it, simply strip each line of the new line character using .strip().

    ip_list = open('/home/daryll/scripts/ip_list')
    for ip in ip_list:
        ip = ip.strip()
        print("set security address-book global address", ip, ip + "/32")

Upvotes: 1

Related Questions