Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gmmastros on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Python Error unpacking hex data 1

Status
Not open for further replies.

6a6f686e

Programmer
Mar 18, 2005
2
0
0
US
Code:
""" I wrote this script to illustrate the problem:
      '\x1a' hex string gets truncated when read from file
   Does anyone know a workaround?
"""
import struct
x = struct.pack('chhh','a', 6668,22,33)
# x is now  'a\x00\x0c\x1a\x16\x00!\x00'

# just to prove that it is working:
print "\noriginal data:\n"+`x`
print "\n\nunpacking original Data is no problem:\n"+ `struct.unpack('chhh',x)`

#now comes the interesting part...
#when 
f = open('test.tmp','w')
f.write(x)
f.close()
f = open('test.tmp','r')
newx = f.read()
try:
    print struct.unpack('chhh',newx)
except:
    print "\n\nBut when I write and retrieve data from file, should be:\n"+`x`+"\n\nbut it's been truncated at \\x1a. See:\n"+`newx`
 
I found the answer here:

U+201A (SINGLE LOW-9 QUOTATION MARK) should be fine, except
that \x1A is converted to EOF on Windows; then expat chokes
on all the unclosed tags.

The Solution:
Open the file 'rb'.
Sen_Wink.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top