0

I am beginner with python. ASCII files I can create, but with binary it seems more difficult to get in. The writing of binary files got me confused, when I have not been able to find simplest code EXAMPLES, which would effectively reveal me, how it is actually done.

So, here I write things, which I would like to solve:

python: a=254, write value a to binary file.

file1: FE file2: 00FE file3: 000000FE file4: FE00 file5: FE000000

python: string="00AABBCCDDEEFF" file: 00AABBCCDDEEFF

python: string="999 This is ASCII" file: 090909[and the rest same way converted]

So, that was writing needs, but how to reverse the progress? Additional explaining, how to read wwxxyyzz from file: FFDD0045wwxxyyzzFA23 python: wwxxyyzz (as value or string) python: zzyyxxww (reversed)

If I could find as basic information, it would help me a lot to the new things to play with. As you may see, this is my first post, so very newbie...

1.st EDIT: Okay, first I thank the fast answer, but as I am so new here, I could not comment, upvoted or so. That example is fitting for my file1, but file2-5 will be still hard to figure out, even with provided links, if there is not as clear and small (full) example. Also my question was rapidly marked as a duplicate, but on there was information still a bit not clear enough for a newbie like me. I have to continue with trial and error.

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63

1 Answers1

0

Heres a basic example that will accomplish what you wanted for writing binary files

>>> filename = "file"
>>> file = open(filename,"wb")
>>> a = 254
>>> file.write(chr(a))
>>> file.close()

For reading binary files, and more examples:

  1. Reading binary file in Python and looping over each byte

  2. https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

  3. Binary file IO in python, where to start?

Community
  • 1
  • 1