Jay Gattuso
Jay Gattuso

Reputation: 4130

Write a "string" as raw binary into a file Python

I'm trying to write a series of files for testing that I am building from scratch. The output of the data payload builder is of type string, and I'm struggling to get the string written directly to the file.

The payload builder only uses hex values, and simply adds a byte for each iteration.

The 'write' functions I have tried all either fall over the writing of strings, or write the ASCII code for the string, rather than the string its self...

I want to end up with a series of files - with the same filename as the data payload (e.g. file ff.txt contains the byte 0xff

def doMakeData(counter):
    dataPayload = "%X" %counter
    if len(dataPayload)%2==1:
        dataPayload = str('0') + str(dataPayload)
    fileName = path+str(dataPayload)+".txt"
    return dataPayload, fileName

def doFilenameMaker(counter):
    counter += 1
    return counter

def saveFile(dataPayload, fileName):
    # with open(fileName, "w") as text_file:
          # text_file.write("%s"%dataPayload)  #this just writes the ASCII for the string
    f = file(fileName, 'wb')
    dataPayload.write(f) #this also writes the ASCII for the string
    f.close()
    return

if __name__ == "__main__":
    path = "C:\Users\me\Desktop\output\\"
    counter = 0
    iterator = 100
    while counter < iterator:
        counter = doFilenameMaker(counter)
        dataPayload, fileName = doMakeData(counter)
        print type(dataPayload)
        saveFile(dataPayload, fileName)

Upvotes: 1

Views: 9762

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177640

To write just a byte, use chr(n) to get a byte containing integer n.

Your code can be simplified to:

import os
path = r'C:\Users\me\Desktop\output'
for counter in xrange(100):
    with open(os.path.join(path,'{:02x}.txt'.format(counter)),'wb') as f:
        f.write(chr(counter))

Note use of raw string for the path. If you had a '\r' or '\n' in the string they would be treated as a carriage return or linefeed without using a raw string.

f.write is the method to write to a file. chr(counter) generates the byte. Make sure to write in binary mode 'wb' as well.

Upvotes: 4

kindall
kindall

Reputation: 184171

dataPayload.write(f) # this fails "AttributeError: 'str' object has no attribute 'write'

Of course it does. You don't write to strings; you write to files:

f.write(dataPayload)

That is to say, write() is a method of file objects, not a method of string objects.

You got this right in the commented-out code just above it; not sure why you switched it around here...

Upvotes: 1

Related Questions