将字符串数据转换为二进制并在Python中解码?

时间:2015-06-03 17:55:35

标签: python

我之前曾问过一个问题,但有点不清楚。

如果我有这一行数据:

52, 123, 0, ./commands/command_fw_update.c, "Testing String"
52, 123, 0, ./commands/command_fw_updat2e.c, "Testing String2"

如何将此数据转换为.bin文件,然后将bin文件中的数据作为字符串读回?

1 个答案:

答案 0 :(得分:0)

数据已经是您想要的格式。如果要将输入文件复制到另一个名为input.bin的文件,请使用shutil.copyfile

# Copy the data to a .bin file:
import shutil
shutil.copyfile("input.txt", "input.bin")

# Read the data as a string:
with open("input.bin") as data_file:
    data = data_file.read()

# Now, to convert the string to useful data, 
# parse it any way you want. For example, to take
# the first number in each line and store it into
# an array called "numbers":
data = [[field.strip() for field in line.split(",")]
        for line in data.splitlines()]
numbers = [int(data[0]) for data in data]
print numbers