Python Forum
Updating a config file [solved]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating a config file [solved]
#1
Hi,

I've a config.py file with the following content:

from mqtt_as import config

config['ssid'] = 'my router'
config['ssid_pw'] = 'pwd'
config['mqtt_user'] = 'user'
config['mqtt_pw'] = 'pwd'
config['pub_topic'] = 'main/esp'  
config['sub_topic'] = 'main/esp/32/relays'
I know how to read from it but how do I modify say, the 'ssid_pw' password string?
TIA
Reply
#2
I'm assuming you just edit it with a text editor and overwrite the placeholders on the right. Unless someone has written a GUI that prompts for it directly.
Reply
#3
(Nov-04-2021, 12:30 AM)bowlofred Wrote: I'm assuming you just edit it with a text editor and overwrite the placeholders on the right. Unless someone has written a GUI that prompts for it directly.
I'm using wifimgr.py library to obtain the ssid/password of a router. So, I need to update the config.py via code which is running in a microcontroller. Don't have access to the config file once burned the code into the mcontroller.
Reply
#4
I'm not sure I understand the environment, but I think you can modify them before you hand the config off to the client. Are you using it something like this?
from mqtt_as import MQTTClient, config
...
client = MQTTClient(config)
If so, you can modify them before handing to the client.

from mqtt_as import MQTTClient, config

ssid, password = get_from_wifimgr() 
config["ssid"] = ssid
config["ssid_pw"] = password
client = MQTTClient(config)
Reply
#5
(Nov-04-2021, 12:53 AM)bowlofred Wrote:
from mqtt_as import MQTTClient, config

ssid, password = get_from_wifimgr() 
config["ssid"] = ssid
config["ssid_pw"] = password
client = MQTTClient(config)
Thanks but in my case it won't work.
For an easy understanding, I worked up this code which gets me closer to a solution but:
filename = "test_file.py"
# open file for writing
my_file = open(filename, "w")
my_file.write("config['ssid'] = 'my_ssid'\n")
my_file.write("config['wifi_pw'] = 'my_pw'\n")
my_file.write("config['mqtt_user'] = 'user'\n")

# open file for reading
my_file = open(filename)
# read the file's entire content
content = my_file.read()
my_file.close()
print('Original file content:')
print(content)
print()

# edit file
new_ssid = 'new_ssid'
new_pw = 'new_pw'
# open file for writing
my_file = open(filename, "w")
text_list = ["config['ssid'] = " + new_ssid + '\n', "config['wifi_pw'] = " + new_pw + '\n']
my_file.writelines(text_list)
# open file for reading
my_file = open(filename)
# read the file's entire content
content = my_file.read()
my_file.close()
print('Edited file content:')
print(content)
Output:
Original file content: config['ssid'] = 'my_ssid' config['wifi_pw'] = 'my_pw' config['mqtt_user'] = 'user' Edited file content: config['ssid'] = new_ssid config['wifi_pw'] = new_pw
it has two errors.
1. It erases the file's content thus showing 2 lines instead of 3 (or more)
2. The new variables' strings are missing quotes.
Reply
#6
Parse each line with the re module
import io
import re

initial = io.StringIO("""\
# spam
config['ssid'] = 'my_ssid'
config['wifi_pw'] = 'my_pw'
config['mqtt_user'] = 'user'
# more spam
""")

pat = re.compile(r"^config\[\'([^']*)\'\]")

def trans(line, dic):
    match = pat.match(line)
    if match and match.group(1) in dic:
        param = match.group(1)
        return f"config['{param}'] = '{dic[param]}'\n"
    else:
        return line
        
dic = {
    'ssid': 'new_ssid',
    'wifi_pw': 'new_pw'
}

lines = initial.readlines()

with io.StringIO() as out:
    for line in lines:
        out.write(trans(line, dic))
    print(out.getvalue())
Output:
# spam config['ssid'] = 'new_ssid' config['wifi_pw'] = 'new_pw' config['mqtt_user'] = 'user' # more spam
ebolisa likes this post
Reply
#7
(Nov-04-2021, 09:18 AM)Gribouillis Wrote: Parse each line with the re module
Thanks, those are the results I'm looking for but the config data is in the config.py file along with some functions. So, I need to read the data, edit it and update the file without affecting the rest of the code within the config.py as shown in my last post.
Reply
#8
(Nov-04-2021, 09:18 AM)Gribouillis Wrote: Parse each line with the re module
Got it! Thank you!!
import io, re

filename = "config.py"
# open file for reading
my_file = open(filename)
# read the file's entire content
content = my_file.read()
my_file.close()
print('Original file content:')
print(content)

initial = io.StringIO(content)
pat = re.compile(r"^config\[\'([^']*)\'\]")


def trans(line, dic):
    match = pat.match(line)
    if match and match.group(1) in dic:
        param = match.group(1)
        return f"config['{param}'] = '{dic[param]}'\n"
    else:
        return line


dic = {
    'ssid': 'new_ssid',
    'wifi_pw': 'new_pw'
}

lines = initial.readlines()
with io.StringIO() as out:
    for line in lines:
        out.write(trans(line, dic))
    new_content = out.getvalue()

# update file
my_file = open(filename, 'w')
my_file.write(new_content)
my_file.close()
# read file
readable_file = open(filename)
read_file = readable_file.read()
print('Updated file content:')
print(read_file)
Reply
#9
You can simplify your code by removing the StringIOs. I used them only to simulate real files contents.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  |SOLVED] Glob JPGs, read EXIF, update file timestamp? Winfried 5 640 Oct-21-2021, 03:29 AM
Last Post: buran
  [SOLVED] Read text file from some point till EOF? Winfried 1 410 Oct-10-2021, 10:29 PM
Last Post: Winfried
  [SOLVED] Input parameter: Single file or glob? Winfried 0 456 Sep-10-2021, 11:54 AM
Last Post: Winfried
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 940 Aug-13-2021, 08:21 PM
Last Post: Winfried
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 632 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B
  [Solved] Plotting data from txt file Laplace12 1 672 Jul-06-2021, 07:14 AM
Last Post: Laplace12
  [Solved] Reading every nth line into a column from txt file Laplace12 7 1,484 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  [Solved] Trying to read specific lines from a file Laplace12 7 1,423 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  [Solved] Using readlines to read data file and sum columns Laplace12 4 962 Jun-16-2021, 12:46 PM
Last Post: Laplace12
  Is there a library for recursive object creation using config objects johsmi96 0 823 May-03-2021, 08:09 PM
Last Post: johsmi96

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020