2010-05-24 61 views
0

我正在寫一個python腳本,它查看常見的計算機文件並檢查它們是否有類似的字節,單詞,雙字。雖然我需要/希望以十六進制格式查看文件,但ande實際上並不能讓python在python中打開一個簡單的文件。我曾嘗試用十六進制作爲編碼codecs.open,但是當我文件描述符操作它總是吐回Python:查看Hex中的所有文件

 File "main.py", line 41, in <module> 
    main() 
    File "main.py", line 38, in main 
    process_file(sys.argv[1]) 
    File "main.py", line 27, in process_file 
    seeker(line.rstrip("\n")) 
    File "main.py", line 15, in seeker 
    for unit in f.read(2): 
    File "/usr/lib/python2.6/codecs.py", line 666, in read 
    return self.reader.read(size) 
    File "/usr/lib/python2.6/codecs.py", line 472, in read 
    newchars, decodedbytes = self.decode(data, self.errors) 
    File "/usr/lib/python2.6/encodings/hex_codec.py", line 50, in decode 
    return hex_decode(input,errors) 
    File "/usr/lib/python2.6/encodings/hex_codec.py", line 42, in hex_decode 
    output = binascii.a2b_hex(input) 
TypeError: Non-hexadecimal digit found 





def seeker(_file): 
f = codecs.open(_file, "rb", "hex") 
for LINE in f.read(): 
     print LINE 
f.close() 

我真的只是想看看文件,對它們進行操作,就好像它是一個十六進制像xxd這樣的編輯器。也有可能一次讀取一個文件可能是一個單詞的增量。

不,這不是功課。

+0

是否有一個原因,他們絕對必須在「十六進制」?畢竟,在十六進制編輯器中看到的十六進制格式實際上只是數據的可視化表示,實際上它是二進制的......字節/字/雙字是二進制值,十六進制只是人類可視化它們的一種更簡單的方法。 – Amber 2010-05-24 00:58:23

+0

以及二進制也會很好,但十六進制是更小和通用的好用。 – Recursion 2010-05-24 01:04:47

回答

4

codecs.open(_file, "rb", "hex")正試圖解碼該文件的內容爲十六進制,這就是爲什麼它會失敗。考慮到你的其他「一次一個字」的目標(我假設你的意思是「計算機詞」,即32位?),你最好將打開的文件封裝到你自己的類中。例如:

class HexFile(object): 
    def __init__(self, fp, wordsize=4): 
     self.fp = fp 
     self.ws = wordsize 
    def __iter__(self): 
     while True: 
      data = self.fp.read(self.ws) 
      if not data: break 
      yield data.encode('hex') 

加上你會發現有幫助的其他效用方法當然。

+0

謝謝亞歷克斯,儘管我必須說我在文件表示之前從未見過這種方法。我拿它HexFile需要一個描述符?也許你可以多解釋一下,如果你有時間的話,我很感興趣。 – Recursion 2010-05-24 01:14:01

+0

Alex正在創建一個封裝類,它封裝了一個文件描述符對象,並允許您在字大小的塊中對其進行迭代。 – Amber 2010-05-24 01:21:39

+0

@Recursion,你只需編碼f = HexFile(open('data','rb'))',然後在f:...中輸入hexword。我不確定「文件表示」是什麼意思,因爲琥珀說這只是一個實用包裝。 – 2010-05-24 01:23:59

1

你可以通過一個整數參數read讀取的字節集數:

32bits = file.read(4) 

您可以尋求在文件中的位置使用seek

file.seek(100) # Seeks to byte 100 
1

如果這將是更清晰...: def hexfile(file_path): fp = open(file_path) while True: data = fp.read(4) 如果沒有數據:打破 打印data.encode(「十六進制」)

FILE_PATH大概是「C:/somedir/filename.ext」 那該多好方法順便說一句,將很好地爲我工作。 :)

相關問題