【问题标题】:Append text after certain word in a file在文件中的某个单词之后附加文本
【发布时间】:2021-11-24 14:55:16
【问题描述】:

我想用 python 在文件中的某个单词之后附加文本。

我们举个例子:-

  • 假设我有一个config.py
  • 文件内容如下:
# Configuration file for my python program
username = '' # plain text username
password = '' # hashed version
  • 我的程序运行后,需要输入用户名和密码
  • 然后程序将密码转换为某个哈希值(例如 md5)
  • 现在我想在配置文件中添加用户名和哈希密码
  • config.py 应该是这样的:
 # Configuration file for my python program
 username = 'example_username' # plain text username
 password = 'sdtbrw6vw456546vb' # hashed version

我该怎么做?

【问题讨论】:

标签: python python-3.x append filesystems write


【解决方案1】:

因为您正在使用配置文件。 python中有一个configparser模块用于此。

例如:

将您的config.ini 定义为:

[APP]
environment = test
debug = true

[DATABASE]
username = test_user
password = test_pass
host = 127.0.0.1s
port = 5432
db = test_db

然后您可以将配置操作为:

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)

还可以查看这篇文章以找到更多选项:From Novice to Expert: How to Write a Configuration file in Python

【讨论】:

  • 是个好主意@vlad siv。我正在构建一个 cli 应用程序(debinux)-config.ini 将有很大帮助!如果你不介意你会在这个项目中帮助我吗? (我给你发一个关于这个想法的粗略草图 - 如果你有兴趣,请给我发电子邮件 [v1b7rc8eb@relay.firefox.com])
  • 我不知道有一个内置的配置文件解析器!你有很好的答案。
【解决方案2】:

这应该可以如你所愿:

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)

但是,如果你想这样做来保存东西,使用 JSON 会更好更容易。

【讨论】:

  • 嘿@WalidSiddik 程序只是运行没有输出或config.py 文件没有变化。
  • @Divinemonk 我已编辑并仔细检查过,请重试
  • 谢谢@WalidSiddik,它起到了黄油的作用——谢谢你的朋友
  • 这可行,但它将替换文件中的所有username = '' / password = '' 行。
  • @VladSiv 只需在 re.sub 的末尾添加一个参数 1(我已编辑)
【解决方案3】:

您也可以使用 json 格式的配置文件。使用 json 的好处是它是清晰可读的,因为它只是一个 key value 对,如下所示:

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

用新值更新json 的代码:

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))

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 2015-04-03
    • 2019-03-12
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2011-04-21
    相关资源
    最近更新 更多