问题
I am a newbie to python scripting. I have to extract data line by line from a text file and then convert each line of data received to bytes or bytearray in my .py file.
i am able to extract the data from the file line by line, but not able to convert that to bytes. The text in the file is as follows:
04/nov/14 09:15:30 4.6 2.3
05/nov/14 09:30:45 3.2
06/nov/14 10:00:00 1.2 3.4 5.6
I am not very sure how to use bitArray or bytes/bytearray to the data for conversion. I am sorry I have no code to show here other than file read operation.
file_read = open("read_me.txt", 'r')
for line_read in file_read:
if line_read != "\n":
print(line_read[:-1])
file_read.close()
Please help me in this regard.
Thanks!
回答1:
Each line that you're getting is now a Unicode string. To convert this to bytes you can do:
line_read_bytes = line_read.encode('UTF-8')
which will give you the string encoded in UTF-8.
You can also create a bytearray using:
line_read_bytearray = bytearray(line_read, 'UTF-8')
来源:https://stackoverflow.com/questions/26792911/how-to-convert-the-data-extracted-from-a-file-to-bytes-in-python