Im a Rookie!
im reading data from a sensor with:
data = ""
dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
data = os.read(dev,16)
print(data)
result: b'1 53 -5 1\n'
I was thinking thats a String but seems to be like a Buffer? Could anyone give me a Tip, how to get the 4 Numbers?
i tried
value1 = data[1]
but the result was a different number..
After read other's answer, I must make a supplement here.
I just figured out that you want to read text file instead of binary file, so the codes above won't work for your situation, but I have a better way to read instead of use binary read.
file = open("/dev/rtlightsensor0", "r")
line = file.readline()
data = [int(each) for each in line.split())
Here I read file as a string instead of bytes because your file is text file. Try it and you will find it's really concise.
Below is my original answer, if one day you need read binary data, it will work.
I'm also a Rookie!
You didn't describe your question clearly enough, so I can just guess that you have 4 32-bit(4 bytes) int in your file, which you want to read into your program.
os.read is a binary file read function, so the variable data you got is bytes instead of list of number. Python can't infer the length your number as it can be 4 32-bit number or 1 128-bit number or something else, so you need to say it explicitly by some way.
There is also a little problem that your data is big endian or little endian? If your data doesn't come from network communication, I suppose it's little endian. If you find data is wrong(for example, unbelievable large), you can try to convert 'big' into 'little'.
So you can finish your code like this:
dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
raw_data = os.read(dev,16)
data = []
data.append(int.from_bytes(raw_data[0:4], 'little'))
data.append(int.from_bytes(raw_data[4:8], 'little'))
data.append(int.from_bytes(raw_data[8:12], 'little'))
data.append(int.from_bytes(raw_data[12:16], 'little'))
print(data)
But DO NOT do it like that because it's really silly. If you can understand the code above, then you can write it better like this:
dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
raw_data = os.read(dev, 16)
data = [int.from_bytes(raw_data[i * 4: (i + 1) * 4], 'little') for i in range(4)]
print(data)
By the way, it's not wise to read binary data like this. Generally speaking, the package numpy is recommended.
It is a byte array. You can convert the byte array to string using decode function
>>> test = b'1 53 -5 1\n'
>>> type(test)
<class 'bytes'>
>>> test[0]
49
>>> test_1 = test.decode("utf-8")
>>> test_1[0]
'1'
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