0

I have a text file that contains something like:

IP_ADD = "10.10.150.3"
BACKUP_IP = "10.10.150.4"

and the code to read it in:

counter = 0
wordList = [None] * 100

with open("config.txt") as f:
    content = f.read().splitlines()

for line in content:
    line = line.split(' ',2)[-1]
    wordList[counter] = line
    counter = counter + 1

which will return to me just the IP Address with the quotes inside wordList.. IE

wordList[0] = "10.10.150.3"

I then try to send an SNMP command using the OID and that IP address. IE

agent.set(MY_OID,wordList[0])

but this doesnt work. If I change it to the following:

agent.set(MY_OID,"10.10.150.3")

it works. What am I missing here?

2
  • 1
    Side note: There is no need to read the entire file with f.read() then split that and then loop over the lines. Just do: for line in f: and loop over each line as it is read from the file. More Pythonic... Commented Aug 30, 2016 at 17:34
  • Second side note: Don't create an empty list using wordList = [None] * 100 Just use word_list=[] at the top and then use word_list.append(new_thing) to add to the list. That eliminates the need for the counter as well. If do need a counter, use enumerate and the initiation and incrementing is automatic... Commented Aug 30, 2016 at 17:39

2 Answers 2

3

From what you wrote it appears that your file has the IP addr in quotes. Hence

 line = line.split(' ',2)[-1]

will return an IP address in quotes as a string, aka

 "\"10.0.0.1\""

This is what you are sending across the wire, which is probably not what you intend to do.

Sign up to request clarification or add additional context in comments.

Comments

0

You almost got it, you just need to strip the double quotes around your IPs. Use strip('"') to do that.

line.split(' ',2)[-1].strip('"')

Your code seems too shabby, no offence. You are doing things many of which are not necessary. You can do it much simply this way:

wordList = []
with open('config.txt') as file:
    for line in file:
        wordList.append(line.split()[-1].strip('"'))

print(wordList)

Output:

['10.10.150.3', '10.10.150.4']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.