在Python中写入文件的实际位置

ram*_*osg 2 python file

我想读取文件中的一行并在一行的n位置插入新行("\n")字符,以便将一个9个字符的行转换为三个3个字符的行,如这个:

"123456789" (before)
"123\n456\n789" (after)
Run Code Online (Sandbox Code Playgroud)

我试过这个:

f = open(file, "r+")
f.write("123456789")
f.seek(3, 0)
f.write("\n")
f.seek(0)
f.read()
Run Code Online (Sandbox Code Playgroud)

- >'123 \n56789'

我希望它不要替换位置n中的字符,而只是在该位置插入另一个("\n")字符.

有关如何做到这一点的任何想法?谢谢

jkp*_*jkp 7

我认为没有办法以你想要的方式做到这一点:你必须从你要插入的位置读入文件的末尾,然后在你希望的位置写下你的新角色它是,然后在它之后写回原始数据.这与C或任何具有seek()类型API的语言的工作方式相同.

或者,将文件读入字符串,然后使用list方法插入数据.

source_file = open("myfile", "r")
file_data = list(source_file.read())
source_file.close()
file_data.insert(position, data)
open("myfile", "wb").write(file_data)
Run Code Online (Sandbox Code Playgroud)