【问题标题】:Editing a line of text file after a word在一个单词之后编辑一行文本文件
【发布时间】:2019-03-12 23:15:00
【问题描述】:

我有一个属性文件,必须通过 python 编辑它。我需要编辑jmx.admin.pwd=SomeRandomPassword 行并将随机密码替换为我自己的密码。我做不到。

文本文件如下所示:

some line
some line
some line
min.pop.password=SomeRandomNumbersWordsCharacters
some line
some line
some line

下面应该是修改后的输出:

some line
some line
some line
min.pop.password=My_Password
some line
some line
some line

非常感谢任何帮助,因为我是 Python 新手。

【问题讨论】:

  • 你能用你迄今为止在 python 中尝试过的内容更新你的问题吗?向我们展示你的努力,以及哪里出了问题。尽可能多地提供有关您的代码的信息。同时使用代码的实际输出更新问题。
  • 通用算法...逐行迭代您的文本文件并匹配“min.pop.password”。当条件匹配时,用你想要的字符串替换它
  • 所以您应该展示到目前为止您尝试过的内容。这个之前的问题可能对你有帮助:stackoverflow.com/questions/17140886/…

标签: python text replace line edit


【解决方案1】:

您可以做的是,首先打开文件,然后将所有行读入列表content,同时从每个行中删除\n。从这里您可以在此列表中搜索您的target,其中包含单词或一些独特的短语,为此我们使用了password。不,我们可以将其设置为target,同时将其拆分为=,并存储target_idx。从这里我们只需将.split('=')target 的第二个索引更改为.join(),然后将.join() 重新组合在一起。现在我们可以将新行phrase 分配给contenttarget_idx,替换旧的target。之后我们可以打开我们的text.txt 备份并使用'\n'.join(content) 写入新的content

with open('text.txt') as f:
    content = [line.strip() for line in f]

for i in content:
    if 'password' in i:
        target = i.split('=')
        target_idx = content.index(i)

target[-1] = 'My_Password'
mod = '='.join(target)

content[target_idx] = mod

with open('text1.txt', 'w') as f:
    f.write('\n'.join(content))

之前

chrx@chrx:~/python/stackoverflow/10.3$ cat text.txt 
some line
some line
some line
min.pop.password=SomeRandomNumbersWordsCharacters
some line
some line
some line

之后

chrx@chrx:~/python/stackoverflow/10.3$ cat text.txt 
some line
some line
some line
min.pop.password=My_Password
some line
some line
some line

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2016-06-29
    相关资源
    最近更新 更多