[Python] 排列組合產生任意大小的檔案

[Python] 排列組合產生任意大小的檔案

最近有個需求是要產生一些測試檔案,

當然內容可以是隨機產生,也可以是把所有可能的排列組合都產生出來~ 

利用這個機會,把 array, binascii, itertools 裡的幾個不常用到的函式都學習了一下囉~

 

參考了這篇文章:List of integers into string (byte array) – python

主要用到的是下面幾個函式:

1. itertools.combinations(): 產生指定序列的所有排列組合

2. array.array(): 將一個 integer list 轉成一個 array of bytes 物件,可以很方便地用 tostring() 轉成 byte 字串,或是用 tofile() 將資料輸出到檔案

3. binascii.crc32(): 用來算某個資料的 CRC32 值

 

下面就是一個簡單的測試程式,用來產生檔案大小 0~3 bytes 的所有可能的檔案內容,

檔名就用檔案內容的 CRC32 值來命名~

應該很容易理解囉~

import array
import binascii
import itertools
# Iterate thru different file sizes
for file_len in xrange(0, 3):
# Iterate thru different byte combinations of specific file size
for byte_list in itertools.combinations(xrange(256), file_len):
# Convert the byte list into an array object
byte_list = array.array("B", byte_list)
# Use CRC32 value as file name
file_name = "crc_0x%08X" % (binascii.crc32(byte_list.tostring()) & 0xffffffff)
# Write bytes to file
with open(file_name, "w") as f:
byte_list.tofile(f)
print "Generated", file_name, "with file size", file_len

 

下面是部分的執行結果:

Generated crc_0x00000000 with file size 0
Generated crc_0xD202EF8D with file size 1
Generated crc_0xA505DF1B with file size 1
Generated crc_0x3C0C8EA1 with file size 1
Generated crc_0x4B0BBE37 with file size 1
Generated crc_0xD56F2B94 with file size 1
......

 

 

//
//

(本頁面已被瀏覽過 368 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料