您可以在python中写入文件的中间内容吗? [英] Can you write to the middle of a file in python?

查看:51
本文介绍了您可以在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"

这篇关于您可以在python中写入文件的中间内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆