0

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:

line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5

How would you do it?

1
  • Could you post your code? Commented Oct 5, 2017 at 12:24

4 Answers 4

4

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.

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
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

where do you rewrite the file ?
@Stéphane Just open the same file in write mode and write the lines in the listlines.
0

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.

Comments

0

If you want to replace 'line 3:' when it's at the line beginning, I would use the following code.

lines = []

with open('filename.txt', 'r') as file:
    for line in file:
        if line.startswith("line 3:"):
            line.replace("line 3:", "line NAME 3:", 1)

        lines.append(line)

if lines:
    with open('filename.txt', 'w') as file:
        file.writelines(lines)

If you want to replace 'line 3:' even when it's not at the line beginning, I would use the following code.

lines = []

with open('filename.txt', 'r') as file:
    for line in file:
        if "line 3:" in line:
            line.replace("line 3:", "line NAME 3:", 1)

        lines.append(line)

if lines:
    with open('filename.txt', 'w') as file:
        file.writelines(lines)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.