-2

I previously asked a question, but it was a bit unclear.

If I have this line of data:

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

How can I convert this data into a .bin file, then read back in the data from the bin file as a string?

ryan
  • 625
  • 3
  • 10
  • 23
  • 1
    What's a .bin file? You can write any kind of data into a file with any kind of extension, so that doesn't give much of a hint as to what kind of conversion you're actually trying to do. – Kevin Jun 03 '15 at 17:57
  • Converting the data to binary would be contained in a .bin file, unless I am mistaken. – ryan Jun 03 '15 at 17:59
  • What form is the data in currently? – Robᵩ Jun 03 '15 at 17:59
  • 2
    possible duplicate of [Convert string to binary in python](http://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python) – Zizouz212 Jun 03 '15 at 17:59
  • The form that I have typed above. – ryan Jun 03 '15 at 17:59
  • I mean, is it in a file? Is in your source code? A database? A web page? – Robᵩ Jun 03 '15 at 18:00
  • It's in a file. info.txt – ryan Jun 03 '15 at 18:02
  • To read the above data as a string, simply do: `with open('info.txt') as data_file: data = data_file.read()`. Tell us more about why you think you need a `.bin` file. – Robᵩ Jun 03 '15 at 18:04

1 Answers1

0

The data is already in your desired format. If you want to copy the input file to another file called input.bin, use 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
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Curious, but how would I be able to take the first number in each line and store it into an array called "numbers" as I parse the binary data. – ryan Jun 03 '15 at 18:19