0

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

           123.1.1.1      qwerty
          123.0.1.1      timmy
          (some text)

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

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

4

4 回答 4

1

一般来说,遍历文件的行是很好的,因此它也适用于大文件。

我的方法是

  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)覆盖输入文件。

于 2013-03-26T12:26:25.230 回答
0

这个功能会做你想要实现的

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);
于 2013-03-26T12:08:16.963 回答
0

不幸的是,在 python 中,你不能简单地更新文件而不重写它。您必须执行以下操作。

假设您有一个名为abcd.txt如下的文件。

abcd.txt

123.1.1.1      qwerty
123.0.1.1      timmy

那么你可以做这样的事情。

 with open('abcd.txt', 'rw+') as new_file:
    old_lines = new_file.readlines() # Reads the lines from the files as a list
    new_file.seek(0) # Seeks back to index 0
    for line in old_lines:
        if old_lines.index(line) == 1: # Here we check if this is the second line
            line = line.split(' ')
            line[-1] = 'New Text' # replace the text
            line = ' '.join(line)
        new_file.write(line) # write to file
于 2013-03-26T12:21:23.683 回答
0

例如:

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)

结果:

      123.1.1.1      qwerty
      123.0.1.1      hey
      (some text)

随意询问您是否需要解释。

于 2013-03-26T11:43:02.350 回答