【问题标题】:replace text with a longer text in a text file on python用python上的文本文件中的较长文本替换文本
【发布时间】:2022-10-14 21:17:12
【问题描述】:

我有一个内容如下的文本文件

1 0.374023 0.854818 0.138672 0.230469
0 0.939941 0.597005 0.118164 0.782552
1 0.826118 0.582643 0.347764 0.803151
1 0.503418 0.822266 0.100586 0.240885

我想用“80”替换开头的“1” 如下所示:

80 0.374023 0.854818 0.138672 0.230469
0 0.939941 0.597005 0.118164 0.782552
80 0.826118 0.582643 0.347764 0.803151
80 0.503418 0.822266 0.100586 0.240885

保持其余内容不变。

【问题讨论】:

  • 文件中的字节是连续的。您不能将文件中的 1 个字节替换为 2 个字节。您必须从文件中读取全部内容。然后进行更改并将完整内容写回文件。

标签: python


【解决方案1】:

尝试分两步打开文件:

with open("a_file.txt","r") as f:
    lines = a.readlines()

lines = ["80"+line[1:] if line[0:2]=="1 " else line for line  in lines]
#OR
lines =["80"+line[1:] if line.split(maxsplit=1)[0] == "1" else line for line  in lines] 

with open("a_file.txt","w") as f:
    for line in lines:
        f.write(line)

【讨论】:

  • 这是有问题的,如果以 1 开头的数字是可能的。例如10 0.37......
  • 请改用line.split(maxsplit=1)[0] == "1"
【解决方案2】:

如果您不需要使用 python,那么可以使用 sed 轻松完成以下操作:

sed -i 's/^1/80/g' input_file.txt

s/<regex>/<replacement>/g 表示将所有出现的<regex> 替换为<replacement>^1regular expression,意思是“匹配行首的任何 '1'”。

或者,以下 python 代码将执行相同的操作:

file = open("input_file.txt")
lines = file.readlines()
outFile = open("input_file.txt", "w")
for line in lines:
    split = line.strip().split(" ")
    split[0] = 80 if (split[0] == "1") else split[0]
    print(*split, file=outFile)

您只需遍历每一行,并将行首的“1”替换为 80。

【讨论】:

    【解决方案3】:

    输入文件包含由 [white] 空格分隔的标记组成的行。如果第一个令牌等于“1”,则将其更改为“80”。

    这可以通过以下方式实现:

    with open('foo.txt', 'r+') as foo:
        lines = foo.readlines()
        foo.seek(0)
        for line in lines:
            if (tokens := line.split())[0] == '1':
                tokens[0] = '80'
            print(*tokens, file=foo)
        foo.truncate()
    

    笔记:

    在这种情况下,实际上不需要使用截断,因为文件大小不会增加,但对于这种读/重写过程来说是一种故障安全模式

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2011-02-26
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      相关资源
      最近更新 更多