2

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()

2 Answers2

3

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"
Shihao Xu
  • 721
  • 1
  • 7
  • 14
  • I don't understand what the function seek() does – low-key Force Mar 04 '21 at 20:37
  • @low-keyForce FYI https://docs.python.org/3/tutorial/inputoutput.html. When you open a file, there is somehing like a cursor (let's just call it a file cursor) pointing to the beginning of the file. When you read or write, the cursor automatically moves to the next location. `f.seek(-4, 2)` moves the cursor to the 4th byte, counting backwards from the end (check the link above for more details). When you run `f.read()` the cursor stops at the end of the file. So you have to move it back to the right position, in order to write the content you want at the right place. – Shihao Xu Mar 04 '21 at 20:42
  • Today I learned that opening a file in `r` mode will let you (over)write to it anyway! Thank you! – Ahmed Fasih Oct 13 '22 at 19:06
-1
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)

FileX
  • 773
  • 2
  • 7
  • 19