如何在Python中更新字典并获取用户输入?

-1 投票
2 回答
762 浏览
提问于 2025-04-18 07:12

我想把某个键(比如 db_hostaddons_path)的值替换成 $$$$。这个键和新的值都需要用户提供。

我的函数应该问用户两个问题:

  1. 你想更新哪个键?
  2. 你想更新成什么值?

如果用户回答 key = db_hostvalue = $$$$$,那么程序就应该在文本文件中更新这个值。

输入的文本文件内容如下:

#Test.txt#
addons_path=/bin/root

admin_passwd = abctest

auto_reload = False

csv_internal_sep = ,

db_host = 90.0.0.1

更新后的文本文件:

#Test.txt#
admin_passwd = abctest

auto_reload = False

csv_internal_sep = ,

db_host = $$$$$

我想替换某个键的值,并把它写入一个文件,然后用新文件替换旧文件。

下面这个函数可以正确地替换文件中的值。那么我该如何根据用户的输入来修改它呢?

def replace_in_file(filename, key, new_value):
    f = open('/Files/test2', "r")
    lines = f.readlines()
    f.close()
    for i, line in enumerate(lines):
        if line.split('=')[0].strip(' \n') == key:
            lines[i] = key + ' = ' + new_value + '\n'
    f = open('Files/test2', "w")
    f.write("".join(lines))
    f.close()

replace_in_file("file.txt", 'db_host', "22222")

2 个回答

0

这可能有效!

def replace_in_file(filename, key, new_value):
    f = open('/home/tactix4/Pictures/Ami/Files/tactix4_replace_key/test2', "r")
    lines = f.readlines()
    f.close()
    for i, line in enumerate(lines):
        if line.split('=')[0].strip(' \n') == key:
           lines[i] = key + ' = ' + new_value + '\n'
    f = open('/home/tactix4/Pictures/Ami/Files/tactix4_replace_key/test2', "w")
    f.write("".join(lines))
    f.close()

replace_in_file("test2", key, value)

key = raw_input("which key you want to update? : ")
value = raw_input("Which value you want to update? : ")
2

如果我理解得没错,你只需要这个:

key = raw_input("which key you want to update? : ")
value = raw_input("Which value you want to update? : ")

这个程序会在每种情况下等待用户输入。然后,'key'和'value'这两个变量会存储用户输入的值……

撰写回答