I want to append text after certain word in a file with python.
Let's take an example :-
- Say I have a
config.py
- Contains of file are as follows:
# Configuration file for my python program
username = '' # plain text username
password = '' # hashed version
- After my programs runs, it takes inputs for username and password
- Then the program converts password to some hash (say md5)
- Now I want to add that username and hashed password in the config file
config.py
should look like this :
# Configuration file for my python program
username = 'example_username' # plain text username
password = 'sdtbrw6vw456546vb' # hashed version
I don't know to do that, can someone please help to solve me this?
CodePudding user response:
This should work as you want:
import re
username = 'the username'
password = 'the hash'
with open('config.py', 'r') as file:
text = re.sub(r"username = '.*?'", f"username = '{username}'", file.read())
text = re.sub(r"password = '.*?'", f"password = '{password}'", text)
with open('config.py', 'w') as file:
file.write(text)
But, If you want to do this to save stuff, using JSON is a lot better and easier.
CodePudding user response:
Since you are working with configuration files. There is a configparser
module in python that is used for this.
For example:
Define your config.ini
as:
[APP]
environment = test
debug = true
[DATABASE]
username = test_user
password = test_pass
host = 127.0.0.1s
port = 5432
db = test_db
Then you can manipulate configuration as:
from configparser import SafeConfigParser
if __name__ == "__main__":
config = SafeConfigParser()
config.read("config.ini")
print(config["DATABASE"]["USERNAME"]) # Prints: test_user
config.set("DATABASE", "USERNAME", "test") # Updates USERNAME to "test"
with open("config.ini", "w") as configfile: # Save config
config.write(configfile)
Also check this article to find more options: From Novice to Expert: How to Write a Configuration file in Python