写入并替换文件中的特定行

2023-12-08

我想替换键的值(即db_host, addons_path) with $$$$.

输入文本文件包含以下内容:

#Test.txt#
addons_path=/bin/root
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = 90.0.0.1

输出文本文件:

#Test2.txt#
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = $$$$$

我想替换特定键的值并将其写入文件中,而不是用新文件替换旧文件。

以下函数为我提供了替换特定键的值的正确输出 导入文件输入 从 pprint 导入 pprint 作为 p

replace_with = '7777'
key = 'db_host'

fileref = open('/Files/replace_key/test','r+')


line = fileref.readline()
config = []
while line:
     split_line = line.split('=')
     if len(split_line ) == 2:
        config.append( ( split_line[0].strip(' \n'),split_line[1].strip(' \n') ) )

     print line
     line = fileref.readline()

fileref.close()
config = dict(config)
print config

config.update({'db_host':replace_with})

p(config)

但我无法将其应用于整个文本文件。


如果您想使用 Python 执行此操作,可以使用以下函数:

def replace_in_file(filename, key, new_value):
    f = open(filename, "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(filename, "w")
    f.write("".join(lines))
    f.close()

replace_in_file("file.txt", 'db_host', "7777")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

写入并替换文件中的特定行 的相关文章

  • 如何从 python 获取 BQL (bLOOMBERG) 查询

    我在 Excel 中使用 BQL 有以下查询 BQL MEMBERS INEMCBI LX Equity type holdings 名称 列 2 行 223 这显示了特定共同基金的证券表 像这样 在此输入图像描述 https i stac
  • 用 Python 编写一个无操作或虚拟类

    假设我有这样的代码 foo fooFactory create 由于种种原因 fooFactory create 可能无法创建实例Foo 如果可以的话我想要fooFactory create 返回一个虚拟 无操作对象 这个对象应该是完全惰性
  • 使用正则表达式解析 Snort 警报文件

    我正在尝试使用 Python 中的正则表达式从 snort 警报文件中解析出源 目标 IP 和端口 和时间戳 示例如下 03 09 14 10 43 323717 1 2008015 9 ET MALWARE User Agent Win9
  • 无法包含外部 pandas 文档 Pycharm v--2018.1.2

    我无法包含外部 pandas 文档Pycharm v 2018 1 2 例如 numpy gt http docs scipy org doc numpy reference generated module name element na
  • VSCode pytest 测试发现失败

    Pytest 测试发现失败 用户界面指出 Test discovery error please check the configuration settings for the tests 输出窗口显示 Test Discovery fa
  • 唯一的图像哈希值即使 EXIF 信息更新也不会改变

    我正在寻找一种方法来为 python 和 php 中的图像创建唯一的哈希值 我考虑过对原始文件使用 md5 和 因为它们可以快速生成 但是当我更新 EXIF 信息 有时时区关闭 时 它会更改总和 并且哈希也会更改 有没有其他方法可以为这些文
  • 使用Python将图像转换为十六进制格式

    我的下面有一个jpg文件tmp folder upload path tmp resized test jpg 我一直在使用下面的代码 Method 1 with open upload path rb as image file enco
  • Python unicode 字符代码?

    有没有办法将 Unicode 字符 插入 Python 3 中的字符串 例如 gt gt gt import unicode gt gt gt string This is a full block s unicode charcode U
  • 我可以使用 dask 创建 multivariate_normal 矩阵吗?

    有点相关这个帖子 https stackoverflow com questions 52337612 random multivariate normal on a dask array 我正在尝试复制multivariate norma
  • 字典中列表中仅有的几个索引的总和

    如果我有这种类型的字典 a dictionary dog white 3 5 black 6 7 Brown 23 1 cat gray 5 6 brown 4 9 bird blue 3 5 green 1 2 yellow 4 9 mo
  • 使用 python 将文本发送到带有逗号分隔符的列

    如何使用分隔符 在 Excel 中将一列分成两列 并使用 python 命名标题 这是我的代码 import openpyxl w openpyxl load workbook DDdata xlsx active w active a a
  • 负整数的Python表示

    gt gt gt x 4 gt gt gt print b format x x 4 100 gt gt gt mask 0xFFFFFFFF gt gt gt print b format x mask x mask 4294967292
  • ValueError:无法插入 ID,已存在

    我有这个数据 ID TIME 1 2 1 4 1 2 2 3 我想按以下方式对数据进行分组ID并计算每组的平均时间和规模 ID MEAN TIME COUNT 1 2 67 3 2 3 00 1 如果我运行此代码 则会收到错误 ValueE
  • 在 Tkinter 中使用锚点

    我正在尝试对自动点唱机进行编程 但是我还处于早期阶段 并且在使用时遇到了问题anchor 这是我的代码 from tkinter import from tkinter import messagebox as box def main m
  • 在谷歌C​​olab中使用cv2.imshow()

    我正在尝试通过输入视频来对视频进行对象检测 cap cv2 VideoCapture video3 mp4 在处理部分之后 我想使用实时对象检测来显示视频 while True ret image np cap read Expand di
  • Python 矩阵每一行的总和

    lista 1 2 3 4 5 6 7 8 9 print lista def filas lista res for elemento in lista x sum lista elemento res append x print re
  • asyncio - 多次等待协程(周期性任务)

    我正在尝试为异步事件循环创建定期任务 如下所示 但是我收到 RuntimeError 无法重用已等待的协程 异常 显然 asyncio 不允许等待相同的可等待函数 如中讨论的这个错误线程 https bugs python org issu
  • 具有指定置信区间的 Seaborn 条形图

    我想在 Seaborn 条形图上绘制置信区间 但我已经计算出置信区间 如何让 Seaborn 绘制我的置信区间而不是尝试自行计算它们 例如 假设我有以下 pandas DataFrame x pd DataFrame Group 1 0 5
  • 使用 Keras 和 fit_generator 绘制 TensorBoard 分布和直方图

    我正在使用 Keras 使用 fit generator 函数训练 CNN 这似乎是一个已知问题 https github com fchollet keras issues 3358TensorBoard 在此设置中不显示直方图和分布 有
  • 如何识别图形线条

    我有以下格式的路径的 x y 数据 示例仅用于说明 seq p1 p2 0 20 2 3 1 20 2 4 2 20 4 4 3 22 5 5 4 22 5 6 5 23 6 2 6 23 6 3 7 23 6 4 每条路径都有多个点 它们

随机推荐