Noobie: Open file -> read characters & multiply

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Dec 26 19:20:02 EST 2006


On Tue, 26 Dec 2006 16:50:06 -0700, gonzlobo wrote:

> I've been using Python for a few days. It's such the perfect language
> for parsing data!
> 
> I really like it so far, but I'm having a hard time reading a file,
> reading the first few hex characters & converting them to an integer.
> Once the characters are converted to an integer, I'd like to write the
> data to another file.
> 
> Here's the code snipped to the bare minimum:
> ---
> # Open File
> AP_File= open("AP.txt", "r")
> decoded_File= open("decoded.txt", "w")
> 
> # read & process data line by line
> for line in AP_File:
>    time = int(hex(line[0:8]), 16) * 0.0001     # this line is completely hosed!
>    decodedFile.write(time)

What does "this line is completely hosed!" mean? Does it crash your PC?
Does it raise an exception? Do the wrong thing?

Try this:

for line in AP_File:
    # Typical line looks like this:
    # 000000d5 26 0600 80 00 ec 80 02 03 7d db 02 33
    # This should convert to:
    # 0.0213 26 0600 80 00 ec 80 02 03 7d db 02 33
    time = int(line[0:8], 16) * 0.0001
    line = str(time) + line[8:]
    decodedFile.write(line)

You might need to think about how many decimal places you want the time to
store.


> My boss and I are trying to complete the same task (he figured out how
> to do it, but his code uses a while != "" loop and doesn't look
> pythony (it looks too 'c'). Not that there's anything wrong with that!



You can convert this:

AP_File= file("AP.txt", "r")  # file is recommended over "open"
line = AP_File.readline()
while line != "":
    do_something_with_line
    line = AP_File.readline()
AP_File.close()


into this:

AP_File= file("AP.txt", "r")
for line in AP_File:
    do_something_with_line
AP_File.close()

You need to look at what your boss does with the lines, not how he does
the loop.


-- 
Steven.




More information about the Python-list mailing list