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
  Python openyxl not updating Excel file MrBean12 1 249 Mar-03-2024, 12:16 AM
Last Post: MrBean12
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 542 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Updating sharepoint excel file odd results cubangt 1 752 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  Loop through json file and reset values [SOLVED] AlphaInc 2 1,959 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  [Solved by deanhystad] Create a zip file using zipfile library DZ_Galaxy 2 1,104 Aug-17-2022, 04:57 PM
Last Post: DZ_Galaxy
  Initializing, reading and updating a large JSON file medatib531 0 1,722 Mar-10-2022, 07:58 PM
Last Post: medatib531
  |SOLVED] Glob JPGs, read EXIF, update file timestamp? Winfried 5 2,410 Oct-21-2021, 03:29 AM
Last Post: buran
  [SOLVED] Read text file from some point till EOF? Winfried 1 1,909 Oct-10-2021, 10:29 PM
Last Post: Winfried
  [SOLVED] Input parameter: Single file or glob? Winfried 0 1,539 Sep-10-2021, 11:54 AM
Last Post: Winfried
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 4,303 Aug-13-2021, 08:21 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

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