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

2024-10-03 06:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我以前问过一个问题,但有点不清楚。你知道吗

如果我有这行数据:

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

如何将此数据转换为.bin文件,然后以字符串形式从bin文件读回数据?你知道吗


Tags: 文件数据字符串stringbinupdatetestingcommand
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:19

数据已经是您想要的格式。如果要将输入文件复制到另一个名为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

相关问题 更多 >