36
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでバイナリファイルを作成する

Last updated at Posted at 2013-08-31

ちょっとしたバイナリファイルをPythonで作成する方法。

import struct

def main():    
    with open("data", "wb") as fout:        
        for x in [0xFF, 0x12, 0x89]:            
            fout.write(struct.pack("B", x))

if __name__ == "__main__":    
    main()

hexdump コマンドで作成したファイルの中身を確認してみます。

% hexdump data
0000000 ff 12 89
0000003

問題なく作れていますね。

(追記 2013-09-07)

shiracamus さんにコメントで bytearray を教えていただきました。こちらの方が import も必要ないので手軽ですね。

def main():
    with open("data", "wb") as fout:
        bary = bytearray([0xFF, 0x12, 0x89])
        bary.append(0)
        bary.extend([1, 127])
        fout.write(bary)

if __name__ == "__main__":
    main()

hexdump の実行結果です。

% hexdump data
0000000 ff 12 89 00 01 7f
0000006
36
42
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?