Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

editing a single .txt line in python 3.1

i have some data stored in a .txt file in this format:

----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces    3292532113435532419963

don't ask...

i have many lines of this, and i need a way to add more digits to the end of a particular line.

i've written code to find the line i want, but im stumped as to how to add 11 characters to the end of it. i've looked around, this site has been helpful with some other issues i've run into, but i can't seem to find what i need for this.

it is important that the line retain its position in the file, and its contents in their current order.

using python3.1, how would you turn this:

1020414646canBeFollowedBySpaces    3292532113435532419963

into

1020414646canBeFollowedBySpaces    329253211343553241996301846372998
like image 966
jtkiv Avatar asked May 10 '26 05:05

jtkiv


1 Answers

As a general principle, there's no shortcut to "inserting" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.

For example:

with open("input.txt") as infile:
    with open("output.txt", "w") as outfile:
        for s in infile:
            s = s.rstrip() # remove trailing newline
            if "target" in s:
                s += "0123456789"
            print(s, file=outfile)
os.rename("input.txt", "input.txt.original")
os.rename("output.txt", "input.txt")
like image 181
Greg Hewgill Avatar answered May 11 '26 19:05

Greg Hewgill