1

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

enter image description here

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?

  • For not-very-large file it would probably be faster to just read the whole file, change the part you need, and write it back. – user202729 Sep 26 '20 at 09:07
  • Do you want to replace those 500 bytes with just 4 bytes (and shift the rest to the left)? – user202729 Sep 26 '20 at 09:07
  • your question isn't very clear. replace the data in [250 - 750] with what? – Tibebes. M Sep 26 '20 at 09:08
  • `open('a.txt')` opens the file for reading by default, so a `f.write()` isn't going to work. You need to read the entire file to get the parts you want to keep, and then re-open the file in write mode and output the two sections you want to retain. – martineau Sep 26 '20 at 09:08
  • Related to [Modifying binary file with Python](https://stackoverflow.com/questions/14643538/modifying-binary-file-with-python) – DarrylG Sep 26 '20 at 09:14
  • @user202729 no, i want to replace the 500 bytes with 500 new bytes of data, not shifting the bytes – kurdish devil Sep 26 '20 at 14:40
  • @martineau i tried to use your method but the performance is too slow, i need to look for a more ideal way – kurdish devil Sep 26 '20 at 14:41

2 Answers2

2

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)
Wups
  • 2,489
  • 1
  • 6
  • 17
  • 1
    this works for txt files, but is there anyway i can achieve the same thing for .mp4 files? – kurdish devil Sep 26 '20 at 16:11
  • 2
    Binary files like .mp4 can be opened with `"r+b"`. The data written to the file should be [bytes](https://docs.python.org/3.8/library/stdtypes.html#bytes). @kurdishdevil – Wups Sep 26 '20 at 16:34
1

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.