我需要在第n个字节后附加到文件而不删除以前的内容.
例如,如果我有一个文件包含:"Hello World"
,我寻求位置(5)写"this"我应该得到
"Hello this world"
有没有我应该打开文件的模式?
目前我的代码替换字符
并给出"Hello thisd"
>>> f = open("1.in",'rw+')
>>> f.seek(5)
>>> f.write(' this')
>>> f.close()
Run Code Online (Sandbox Code Playgroud)
有什么建议?
你无法insert在文件中使用.通常做的是:
在python中它应该是这样的:
nth_byte = 5
with open('old_file_path', 'r') as old_buffer, open('new_file_path', 'w') as new_buffer:
# copy until nth byte
new_buffer.write(old_buffer.read(nth_byte))
# insert new content
new_buffer.write('this')
# copy the rest of the file
new_buffer.write(old_buffer.read())
Run Code Online (Sandbox Code Playgroud)
现在你必须Hello this world进来new_buffer.在那之后,由你来决定是否用新的或者你想用它做什么来覆盖旧的.
希望这可以帮助!