Learn, Share, Build

269
October 05, 2017, at 4:14 PM

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?

Answer 1
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)
Answer 2

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.

Answer 3

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
Rent Charter Buses Company
READ ALSO
Learn, Share, Build

Learn, Share, Build

I'm trying to traverse an ftp directory using FTPwalker, however I cannot connect

354
Learn, Share, Build

Learn, Share, Build

I am trying to use the BeautifulSoup library in Python to extract the jpg image names from a html scriptIn the url wherever you find srcset it is always proceeded by a jpg file name

271
Learn, Share, Build

Learn, Share, Build

I try to connect mongodb database using mongoengine with dynamic connectioni getting database name from URL Request

273
Learn, Share, Build

Learn, Share, Build

I have a code block within transactionatomic() within a view

254