I would like to write to the middle of a line in a file.
for exemple i have a file:
Text.txt:
JavaScript
2
1
"i would like to insert information over here >>>>>>>[]<<<<<<<<"
2
Is is it possible to precise an index where: file.write()
has to start writing?
I have started with this:
JavaScript
3
1
file = open(file_path, 'w')
2
file.write()
3
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:
JavaScript
11
1
with open('text.txt', 'w') as f:
2
f.write("0123456789")
3
4
# now the file 'text.txt' has "0123456789"
5
6
with open('text.txt', 'r+b') as f:
7
f.seek(-4, 2)
8
f.write(b'a')
9
10
# now the file 'text.txt' has "012345a789"
11
Insert:
JavaScript
13
1
with open('text.txt', 'w') as f:
2
f.write("0123456789")
3
4
# now the file 'text.txt' has "0123456789"
5
with open('text.txt', 'r+b') as f:
6
f.seek(-4, 2)
7
the_rest = f.read()
8
f.seek(-4, 2)
9
f.write(b'a')
10
f.write(the_rest)
11
12
# now the file 'text.txt' has "012345a6789"
13