[英]Python - Add string after a word in a specific line of a file
I need to add string after a word in a specific line of a text file. 我需要在文本文件的特定行中的单词之后添加字符串。 The original file is:
原始文件是:
line 1: value1
line 2: value2
line 3: value3
line 4: value4
line 5: value5
For example, I want to add "NAME" in the line number 3 just after "line" so the file would become: 例如,我想在“行”之后的第3行中添加“名称”,这样文件将变为:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
How would you do it? 你会怎么做?
This looks for line that starts with “line 3:” and edits just this line, retains the rest as is, and writes the text to a new file. 这将查找以“第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)
When you run the code below, 当您运行以下代码时,
with open('f2.txt', 'r') as f:
for line in f:
print(line, end='')
It prints: 它打印:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
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)
I would consider this: 我会考虑一下:
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)
It's true that it seems highly inefficient (and probably not realistic for a large file). 确实,它似乎效率很低(对于大文件来说可能不现实)。 I would be curious to see better ways.
我很想知道更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.