0

I have a text file which contains this information:

 network={
      ssid="WIFI_SSID"
      scan_ssid=1
      psk="WIFI_PASSWORD"
      key_mgmt=WPA-PSK
}

I want to modify this text file and change the ssid and psk values. so I want something like this:

network={
      ssid="KB150"
      scan_ssid=1
      psk="testpass"
      key_mgmt=WPA-PSK
}

I wrote this code, but it only can add a new line at end of the file only for ssid (something like ssid= KB150):

if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"
    with open("example.txt", 'r+') as outfile:
        for line in outfile:
            if line.startswith("ssid"):
                sd = line.split("= ")
                outfile.write(line.replace(sd[1], ssid))
            if line.startswith("password"):
                pw = line.split("= ")
                line.replace(pw[1], password)
                outfile.write(line.replace(pw[1], ssid))

    outfile.close()

The values of ssid and psk change whenever a user enter an input in my program, so I need to find the line that starts with those keywords and change their values.

3 Answers 3

1

Since the file is small, you can read it fully, do the replacement and write back. You don't have to close it explicitly as with handles it.

if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"
    # open for reading
    with open("example.txt", 'r') as infile:
        content = infile.read()
    # reopen it for writing
    with open("example.txt", 'w') as outfile:
        content = content.replace("WIFI_SSID", ssid).replace("WIFI_PASSWORD", password)
        outfile.write(content)

Modifying file while reading is tricky. Discussed here

Edit

There are multiple ways to handle it. You can keep a template file with the content.

network={

      ssid="WIFI_SSID"
      scan_ssid=1
      psk="WIFI_PASSWORD"
      key_mgmt=WPA-PSK
}

The script can read the content of template file, replace ssid and password and write to target file.

Another way is to use regex replacement like

import re
if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"

    with open("example.txt", 'r') as infile:
        content = infile.read()

    # reopen it for writing
    with open("example.txt", 'w') as outfile:
        content = re.sub('ssid="[^"]*"', f'ssid="{ssid}"', content)
        content = re.sub('psk="[^"]*"', f'psk="{password}"', content)
        outfile.write(content)
Sign up to request clarification or add additional context in comments.

1 Comment

Useful tip. thanks. But I need to change this file multiple times, every time I want to connect to wifi, so, I need to find a line which starts with "ssid" and "password" and change them, these values are not fixed.
0

I would guess your line.startswith("ssid") is not returning True, because in your example.txt are whitespaces before "ssid". So you maybe want to think about spliting the line with the right amound of whitespaces or search for ssid in every line.

2 Comments

I had some changes in my example here. In my text file, I only create a file with two lines like this: ---- ssid= "WIFI_SSID" password= "WIFI_PASSWORD" ---- still, cannot change the values of them.
@Shanavas M was faster than me!
0

Thanks to Shanavas M (having his useful tip in my mind), My friend helped me and I got finally what I want:)

fileName = 'example.txt'
    result = ""
    ssid = "KB150"
    password = "testpass"

    with open(fileName, 'r') as filehandle:
        for line in filehandle:
            temp = line.split('=')[0]
            if temp == "ssid ":
                result += 'ssid = "{}"\n'.format(ssid)
            elif temp == 'password ':
                result += 'password = "{}"\n'.format(password)
            else:
                result += line

    with open(fileName, 'w') as filehandle:
        filehandle.write(result)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.