Skip to content Skip to sidebar Skip to footer

Can You Write To The Middle Of A File In Python?

I would like to write to the middle of a line in a file. for exemple i have a file: Text.txt: 'i would like to insert information over here >>>>>>>[]<<&l

Solution 1:

I think what you can do is to substitute already existing characters with the same amount of other characters you want. You can open a file, locate the starting point, and start writing. But you will overwrite all the following bytes if you use f.write(). If you want to "insert" something inbetween, you have to read and rewrite all the following content of the file.

Overwrite:

withopen('text.txt', 'w') as f:
    f.write("0123456789")

# now the file 'text.txt' has "0123456789"withopen('text.txt', 'r+b') as f:
    f.seek(-4, 2)
    f.write(b'a')

# now the file 'text.txt' has "012345a789"

Insert:

with open('text.txt', 'w') as f:
    f.write("0123456789")

# now the file 'text.txt' has "0123456789" 
with open('text.txt', 'r+b') as f:
    f.seek(-4, 2)
    the_rest = f.read()
    f.seek(-4, 2)
    f.write(b'a')
    f.write(the_rest)

# now the file 'text.txt' has "012345a6789"

Solution 2:

import fileinput


file = [The file where the code is]    

for line in fileinput.FileInput(file, inplace=1):
    if [The text that should be in that line] in line:
        line = line.rstrip()
        line = line.replace(line, [The text that should be there after this file was run])

    print (line,end="")

As text in that line you should enter the whole line, else it could not work (I didn't test it out though)

Post a Comment for "Can You Write To The Middle Of A File In Python?"