Home > Mobile >  Append text after certain word in a file
Append text after certain word in a file

Time:10-05

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

How can I do that?

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

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(), 1)
    text = re.sub(r"password = '.*?'", f"password = '{password}'", text, 1)


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:

You can also use your config file as a json format. Benefit of using a json is it is clearly readable as it's just a key value pair, as below:

{"username": "test_user", "password": "test_password", "host": "127.0.0.1s", "port": "5432", "db": "test_db"}

The code to update the json with the new values:

import json

with open ("config.json", "r") as config_file:
    config_data = json.loads(config_file.read())
# Update the data
config_data["username"] = "new_user"
config_data["password"] = "sdtbrw6vw456546vb"
with open ("config.json", "w") as config_file:
    config_file.write(json.dumps(config_data))
  • Related