假设我的文件包含(只读):
123.1.1.1 qwerty
123.0.1.1 timmy
(some text)
我想把timmy
改成一些新的单词,但是我不应该在代码的任何地方使用单词"timmy",因为用户可以随时更改它。
在python中可能"转到特定行并替换最后一个单词"吗?
一般来说,迭代文件的行是好的,因此它也适用于大文件。
我的方法是
- 逐行读取输入
- 拆分每一行
- 替换第二行
- 重新连接部件
- 写入文件
我将每行分开并再次连接,以便在单词之间的空白处保持一致性。如果你不关心它,保持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)
结果: 123.1.1.1 qwerty
123.0.1.1 hey
(some text)
如果你需要解释,尽管问。
此函数将执行您想要实现的功能
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);
不幸的是,在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