简体   繁体   中英

how to write to a specific part of file?

i want replace a specific part of file by bytes, here's an ugly image to explain what i want to achieve:-

在此处输入图片说明

i tried to do it with this code

f=open('a.txt')
f.seek(250, os.SEEK_SET)
print(f.read(750))

it works fine, but it only reads the file, not actually writes to the file. i tried to use this code

f=open('a.txt')
f.seek(250, os.SEEK_SET)
print(f.write('data', 750))

but write only takes 1 argument, so i can't use write command.

are there any methods i can achieve this in python?

Open the file in the appropriate mode , seek the position you want and write the amount of bytes you want to replace. To replace everything from position 250 to 750, you need to write 500 bytes.

Bytes isn't really correct in this case though, because it seems to be a text file and it is opened in text mode. Use "r+b" if you really wanted binary mode.

with open("a.txt", "r+") as f:
    f.seek(250)
    print(f.read(500))
    f.seek(250)
    f.write("X"*500)

You should use open('a.txt', 'r+'), the first answer to this question How to open a file for both reading and writing? has a good set up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM