我需要在文本文件的特定行中的单词后面添加字符串。原始文件是:
line 1: value1
line 2: value2
line 3: value3
line 4: value4
line 5: value5
例如,我想添加" NAME"在" line"之后的第3行所以文件将成为:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
你会怎么做?
答案 0 :(得分:1)
这将查找以“第3行:”开头的行,并仅编辑此行,保留其余部分,并将文本写入新文件。
with open('f1.txt', 'r') as f:
lines = []
for line in f:
if line.startswith("line 3:"):
split_line = line.split()
split_line.insert(split_line.index("3:"), "NAME")
lines.append(' '.join(split_line) + '\n')
else:
lines.append(line)
with open('f2.txt', 'w') as f:
for line in lines:
f.write(line)
当您运行以下代码时,
with open('f2.txt', 'r') as f:
for line in f:
print(line, end='')
打印:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
答案 1 :(得分:0)
with open(file, 'r') as f:
lines = []
for line in f:
split_lines = line.split(':')
if split_lines[0].endswith('3') is True:
lines.append(split_lines[0][:-1] + NAME + split_lines[1:])
else:
lines.append(line)
答案 2 :(得分:0)
我会考虑这个:
line_number = 3#I understood you know this. right ?
string_to_add = "NAME"#I understood you know this. right ?
string_to_find = "line"#I understood you know this. right ?
filename = "toto"
with open(filename,"r") as f:
s = f.readlines()
s[line_number] = s[line_number].replace(string_to_find,string_to_find+string_to_add)
with open(filename,"w") as f:
for line in s:
f.write(line)
这似乎非常低效(对于大文件可能不太现实)。我很想看到更好的方法。