使用python中的file input或regex只替换“文件中第二行的最后一个单词”

2024-04-20 09:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的文件包含(只读):

           123.1.1.1      qwerty
          123.0.1.1      timmy
          (some text)

我想把timmy改成新单词,但我不应该在代码中的任何地方使用“timmy”,因为用户可以随时更改它。在

在python中“转到特定行并替换最后一个单词”是否可能?在


Tags: 文件代码text用户地方some单词timmy
3条回答

一般来说,迭代文件的行是好的,因此它也适用于大文件。在

我的方法是

  1. 逐行读取输入
  2. 拆分每行
  3. 如果在第二行,则替换第二个单词
  4. 把零件重新连接起来
  5. 写入输出文件

我把每一行分开,然后再把它连接起来,以便在单词之间有一些一致的空格。如果您不关心它,请保持line不变,除非idx == 1。然后您还可以break第2行之后的循环(idx==1)。在

import shutil

input_fn = "15636114/input.txt"
output_fn = input_fn + ".tmp"

replacement_text = "hey"

with open(input_fn, "r") as f_in, open(output_fn, "w+") as f_out:
    for idx, line in enumerate(f_in):
        parts = line.split()
        if idx==1:
            parts[1] = replacement_text
        line = "    ".join(parts) + "\n"
        f_out.write(line)

shutil.move(output_fn, input_fn)        

我写入一个临时输出文件(为了在异常情况下保持输入文件不变),然后最后用输出文件(shutil.move)覆盖输入文件。在

例如:

text = """123.1.1.1      qwerty
          123.0.1.1      timmy
          (some text)
"""

import re
print re.sub(r'^(.*\n.*)\b(\w+)', r'\1hey', text)

结果:

^{pr2}$

如果你需要解释,尽管问。在

此函数将执行您希望实现的操作

def replace_word(filename, linenum, newword):
    with open(filename, 'r') as readfile:
        contents = readfile.readlines()

    contents[linenum] = re.sub(r"[^ ]\w*\n", newword + "\n", contents[linenum])

    with open(filename, 'w') as file:
        file.writelines(contents);

相关问题 更多 >