Reputation: 1140
here is my code.
query = cgi.parse_multipart(rfile, pdict)
upfilecontent = query.get('file')
here, I want to save upfilecontent[0]
to a file in binary mode.
TIA
Upvotes: 0
Views: 1809
Reputation: 123481
From the latest information in you question it sounds like you want to write a byte stream to a file in binary. As earlier answers have shown, this is easy, just make sure to first open the file in binary mode (the trailing 'b' in the second argument to open).
f = open("output_file_name", "wb")
f.write(upfilecontent[0])
f.close()
If that doesn't work, try printing out repr(upfilecontent[0][:64])
. If the result looks like a series of hex digits without leading 0x
's, then you'll need to decode it into byte values before writing.
Upvotes: 0
Reputation: 8732
def writeBinaryData(binaryData):
f = open("data.bin", "wb")
f.write(binaryData)
The "b" in the mode string for a file specifies that you want to read/write binary data.
However, you're example looks like you'll key_1's value is a hexadecimal string "0x330xba" that you'll need to convert to binary first.
Upvotes: 0
Reputation: 61615
Since the value is already a str
, all you have to do is open the file in binary mode and .write()
it:
with file('name.bin', 'wb') as f: # 'w' for writing, 'b' for binary
f.write(d['key_1'])
If you wanted to re-interpret the text as actually being some kind of hex dump, or something else, then you'll have to be more specific.
Upvotes: 2