I am sequentially logging data packets from multiple streams. Depending on the data in each packet, I need to write the data to a specific log file. I will have up to 8 files open at a time to cater for a maximum 8 concurrent data streams The log files are opened and closed at the start and finish of a new data stream.
I have come up with the following code to handle the write operations.
#Identify where the data needs to be stored
filePointer = unpack_from('!B',payload, 4)
#Grab the data
capData = unpack_from('!160s', payload, 10)
#Store the data
if filePointer[0] == 1: Logfile1.write(str(capData[0]))
elif filePointer[0] == 2: Logfile2.write(str(capData[0]))
elif filePointer[0] == 3: Logfile3.write(str(capData[0]))
elif filePointer[0] == 4: Logfile4.write(str(capData[0]))
elif filePointer[0] == 5: Logfile5.write(str(capData[0]))
elif filePointer[0] == 6: Logfile6.write(str(capData[0]))
elif filePointer[0] == 7: Logfile7.write(str(capData[0]))
elif filePointer[0] == 8: Logfile8.write(str(capData[0]))
Is there a nicer more pythony way to do this?
Can a variable be somehow used to make up the file handle or return the required file handle?
Cheers
Pob
You can build a dictionary of filepointers and use it to dynamically select the file:
d = {1: Logfile1, 2: Logfile2, ...}
curr_file = d[filePointer[0]]
curr_file.write(str(capData[0]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With