Skip to content
Advertisement

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 >>>>>>>[]<<<<<<<<"

Is is it possible to precise an index where: file.write() has to start writing?

I have started with this:

file = open(file_path, 'w')
file.write()

Advertisement

Answer

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:

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)
    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"
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement