I'm a total beginner in python and i have a set of byte values in a CSV file which i want to process. Sample values are mentioned below
"b'\xaa'"
"b'\x04'"
data1 = pd.read_csv("test.csv", usecols=[1])
for value in data1.values.flatten():
print(int.from_bytes(value, byteorder='big'))
When running the above code i get the error saying
TypeError: cannot convert 'str' object to bytes
because it is read as a string. How could I pass this string as bytes and use it in the above code?
I'm using Python 3.7.
abhilb
5,7672 gold badges22 silver badges26 bronze badges
asked Dec 22, 2019 at 18:55
Lakshin Karunaratne
4651 gold badge6 silver badges20 bronze badges
1 Answer 1
You can try
>>> x = "b'\xaa'"
>>> int.from_bytes(x.encode('utf-8'), byteorder="big")
421573863975
>>> x = "b'\x04'"
>>> int.from_bytes(x.encode('utf-8'), byteorder="big")
1646724135
answered Dec 22, 2019 at 19:13
abhilb
5,7672 gold badges22 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
blueteeth
I suspect this is the wrong answer because presumably this string is created by doing
str(int.to_bytes(170, length=1, byteorder='big')). The reverse would be extracting \xaa and finding the integer value of that (which is 170).Lakshin Karunaratne
Yes blueteeth is correct. This answer is wrong. If the string is "b'\xaa'" I want to retrieve 170.
lang-py