如何将从文件中提取的数据转换为python中的字节? [英] How to convert the data extracted from a file to bytes in python?

查看:53
本文介绍了如何将从文件中提取的数据转换为python中的字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python脚本的新手。我必须从文本文件中逐行提取数据,然后将接收到的每一行数据转换为.py文件中的字节或字节数组。

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

我不太确定如何使用bitArray或bytes / bytearray进行数据转换。
很抱歉,除了文件读取操作之外,我没有其他代码可以显示。

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()

请帮助我在这方面。

谢谢!

推荐答案

现在得到的每一行都是一个Unicode字符串。要将其转换为字节,您可以执行以下操作:

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')

这将为您提供以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')

这篇关于如何将从文件中提取的数据转换为python中的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆