binary data into long/float

Sandeep Avinash Gohad gohadbhai at rediffmail.com
Mon Nov 1 05:25:57 EST 2004


An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041101/297e424a/attachment.html>
-------------- next part --------------
  

Hello

I am using the following  program to read a file in binary mode and then convert it into Long or float data.
but in few fields the data is not consistent,so it sometimes can be float and sometimes long, but the program do not give any error like
"invalid datatype".
now if i want to set condition for some fields ,like if the number in that particular field is greater than 10000000 then use float else Long how can i set such type of condition?

Regards
Sandeep


import array

def readLong(f00):
    arr = array.array('L') 
    arr.fromfile(fin,1) 
    return arr.tolist()[0] 

def readFloat(f00):
    arr = array.array('f')
    arr.fromfile(fin,1)
    return arr.tolist()[0]

def readThreeLongAndOneFloat(f00):
    """Reads 3 longints, one float and again 3 longints from file fin"""
    long1 = readLong(f00)
    long2 = readLong(f00)
    long3 = readLong(f00)
    float1 = readFloat(f00)
    ong4 = readLong(f00)
    ong5 = readLong(f00)
    long6 = readLong(f00)
    return (long1, long2, long3,float1, long4, long5, long6)


def createCSVLine(threeLongAndOneFloatTuple):
     lst = map(lambda x:str(x), threeLongAndOneFloatTuple[0:7])
     return ','.join(lst) + '\n'


f00 = open("c:/20041029.abc","rb")
outputlist = [] 

run = 1
while run:
    try:
        tup = readThreeLongAndOneFloat(f00)
    except EOFError: 
        run=0
    else:
        outputlist.append(createCSVLine(tup)) 


f00.readline()
f00.close()

# send all the lines accumulated to the output file.

fo=open("c:/20041029.csv","w")
fo.writelines(outputlist)
fo.close()



More information about the Python-list mailing list