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.
CodePudding user response:
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)
CodePudding user response:
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.
