Write a “string” as raw binary into a file Python

家住魔仙堡 提交于 2019-12-01 12:52:06

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.

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...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!