0

Background Information

I have a program that I'm using for pinging a service and printing the results back to a window. I'm currently trying to add to this program, by adding a kind of 'settings' file that users can edit to change the a) host that is pinged and b) timeout

What I've tried so far

file = open("file.txt", "r")
print (file.read())
settings = file.read()

# looking for the value of 'host'

pattern = 'host = "(.*)'
variable = re.findall(pattern, settings)[0]
print(test)

As for what is contained within the file.txt file:

host = "youtube.com"
pingTimeout = "1"

However, my attempts have been unsuccessful as this comes up with the following error:

IndexError: list index out of range

And so, my question is:

Can anyone point me in the right direction to do this? To recap, I am asking how I can take an input from file (in this case host = "youtube.com" and save that as a variable 'host' within the python file).

Chris
  • 351
  • 2
  • 4
  • 13
  • 3
    `file.read` will exhaust the file object, so `settings` is an empty string. Do `settings = file.read()` first and then `print(settings)`. – Patrick Haugh Feb 12 '18 at 00:07
  • Thanks, this makes sense. :) is all working now – Chris Feb 12 '18 at 00:09
  • Possible duplicate of [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file) – wwii Feb 12 '18 at 00:10
  • I do not need to read twice, I didn't realise that was causing an issue however. – Chris Feb 12 '18 at 00:14

2 Answers2

0

First, as Patrick Haugh pointed out, you can't call read() twice on the same file object. Second, using regex to parse a simple key = value format is a bit overkill.

host, pingTimeout = None,None # Maybe intialize these to a default value
with open("settings.txt", "r") as f:
    for line in f:
        key,value = line.strip().split(" = ")
        if key == 'host':
            host = value
        if key == 'pingTimeout':
            pingTimeout = int(value)

print host, pingTimeout

Note that the expected input format would have no quotes for the example code above.

host = youtube.com
pingTimeout = 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Thanks for the response, this seems a little easier. I think I'll use this. However the issue with this is that the outputs contain the " " from the file, how would I solve this? (without having to remove them for the file, as I want to keep them for formatting reasons) – Chris Feb 12 '18 at 00:14
  • @Chris, You can use the `strip()` function call with `"` as the input. – merlin2011 Feb 12 '18 at 00:22
0

I tried this, it may help :

import re
filename = "<your text file with hostname>"
with open(filename) as f:
   lines = f.read().splitlines()

for str in lines:
   if re.search('host', str):
      host, val = str.split('=')
      val = val.replace("\"", "")     
      break 

host = val    
print host
f.close()