THIS SHOULD BE EASY! But i've been unable to find the answer to this question.
Using python, I want to read a binary file into memory, modify the first four bytes of the file, and then write the file back.
There has 开发者_开发技巧to be a simple way to edit four measly bytes! right?
Why read the entire file to change four bytes at the beginning? Shouldn't this work?
with open("filename.txt", "r+b") as f:
f.write(chr(10) + chr(20) + chr(30) + chr(40))
Even if you need to read these bytes from the file to calculate the new values, you could still do:
with open("filename.txt", "r+b") as f:
fourbytes = [ord(b) for b in f.read(4)]
fourbytes[0] = fourbytes[1] # whatever, manipulate your bytes here
f.seek(0)
f.write("".join(chr(b) for b in fourbytes))
with open(filename, 'r+b') as f:
bytes = f.read(4)
newbytes = 'demo'
f.seek(0)
f.write(newbytes)
C:\junk>copy con qwerty.txt
qwertyuiop
^Z
1 file(s) copied.
C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('qwerty.txt', 'r+b')
>>> f.write('asdf')
>>> f.close()
>>> open('qwerty.txt', 'rb').read()
'asdftyuiop\r\n'
>>>
Simply, but memory inefficiently,
The Python 3 way:
def binaryedit(fn):
f=open(fn,mode='rb')
fc=f.read()
f.close()
return b'rawr'+fc[4:]
The Python 2 way:
def binaryedit(fn):
f=open(fn,mode='rb')
fc=f.read()
f.close()
return 'rawr'+fc[4:]
If the files are huge, you can memory map them and edit/write just the bytes that need to change. There's barely any difference until they get over a meg or so, though.
This looks a lot like HW so I will not give exact code. but here is enough information
- You dont need to read the whole file into memory for changing the first 4 bytes
- Open the file in mode 'r+b'
- Use f.seek(0) to seek to the begining
- Write 4 bytes of data using f.write('ABCD')
- Close the file
this should help. http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.html
import Numeric as N import array
num_lon = 144 num_lat = 73 tmpfile = "tmp.bin"
fileobj = open(tmpfile, mode='rb') binvalues = array.array('f') binvalues.read(fileobj, num_lon * num_lat)
data = N.array(binvalues, typecode=N.Float)
data = N.reshape(data, (num_lat, num_lon))
fileobj.close()
精彩评论