0

I want to write 8 bit unsigned integers to file. In c++ we can do it using fprintf in which the format is:

%[flags][width][.precision][length]specifier

Is there any way I can do it using python? I tried finding the size of the file by asigning value of x =1 to print only 9 integer values, I didn't understand how the file size was 35 bytes.

f = open('myfile','w')
while x>0:
for i in range(0,9):
    a[i] = random.randint(0,255)
    f.write("%d" % a[i])
    f.write(" ")
f.write('\n')
x = x-1
f.close()

size of myfile

4
  • 1
    Your code writes the textual, decimal representation of numbers in the range 0-255. Your prose indicates that you want to write the non-textual binary representation. Do you understand the difference? If so, which do you actually want? Commented Apr 1, 2016 at 17:41
  • why shouldn't it be? you're getting some random integer from 0->255, and since you're writing out to a text file, you're getting the string representation of that number, 1 is one character/byte, 10 is two characters/bytes, 100 is 3 characters/bytes, and youre randint() just happened to generate numbers that come to 24 chars/bytes (+ 10 spaces + newline) Commented Apr 1, 2016 at 17:43
  • No , I don't understand the difference :-( @Robᵩ Commented Apr 1, 2016 at 17:53
  • @MarcB I understand what you saying but I don't want to write string representation of the number, how do I write the number? Commented Apr 1, 2016 at 17:58

2 Answers 2

2

The following code writes nine 8-bit unsigned integers a file, using 1-byte-per-word binary representation.

import struct
import random

f = open('myfile','wb')
for i in range(0,9):
    a = random.randint(0,255)
    f.write(struct.pack("=B", a))
f.close()

The important features of this program are:

  • it uses mode 'wb', not 'w' to open the output file.

  • it uses struct.pack to create the binary data.

Sign up to request clarification or add additional context in comments.

1 Comment

By "this code", for a minute I thought you meant the OP's and was really confused. Perhaps clarify.
0

You need to open the file in binary mode and convert the unsigned integer value into a one character string. Here's a simple way of doing it:

import random

with open('myfile', 'wb') as f:
    for _ in range(0, 9):
        a = random.randint(0, 255)
        f.write(chr(a))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.