您可以在python中写入文件的中间内容吗?

问题描述:

我想写到文件中一行的中间.

I would like to write to the middle of a line in a file.

例如,我有一个文件:

Text.txt:

"i would like to insert information over here >>>>>>>[]<<<<<<<<"

是否可以在以下位置精确索引: file.write()必须开始写入?

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

我从这里开始:

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

我认为您可以用已经存在的其他字符替换所需数量的其他字符.您可以打开一个文件,找到起点,然后开始写入.但是,如果使用 f.write(),您将覆盖以下所有字节.如果您想插入",在这两者之间,您必须读取和重写文件的以下所有内容.

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.

覆盖:

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"

插入:

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"