2017-09-15 85 views
-1

我有一個帶有十六進制行的文本文件。我希望每行都轉換成jpeg.file,因爲它們是照片。我能做到這一點單獨使用binascii.a2b_hex像這樣(我已經縮短了十六進制):迭代十六進制來創建jpeg文件

data = binascii.a2b_hex("FFD8FFE") 
with open('image.jpg', 'wb') as image_file: 
    #image_file.write(data) 

現在,我想這是散裝的。所以我有一個帶有十六進制行的文本文件,我希望每個十六進制都寫入他自己的jpeg文件。我想,我幾乎沒有,但我的代碼給了我這個錯誤:

ValueError: too many values to unpack 

下面是代碼:

import binascii 
text_file = open("photos-clean.txt", "w") 

#for each hexadecimal, put it in between single quotes so it becomes a string. Also remove the first two chars from a line. 
with open('photos.txt', 'r') as f: 
    for i in f: 
     photo = i[2:] 
     quotes = "'" + photo.rstrip() + "'" 
     print quotes 
     text_file.write(quotes) 
     text_file.write("\n") 

text_file.close() 

#for each hexadecimal, transform it to a jpeg with binascii and write it to his own jpeg.file 
with open("photos-clean.txt", "r") as f2: 
    for i, data in (f2): 
     transform = binascii.a2b_hex(i) 
     with open('photo{}.jpg'.format(transform), 'wb') as output: 
      output.write(data) 

編輯:我找到了答案,這是我應該做了:

import binascii 
text_file = open("photos-clean.txt", "w") 


with open('photos.txt', 'r') as f: 
    for i in f: 
     photo = i[2:] 
     text_file.write(photo) 
     text_file.write("\n") 

text_file.close() 


with open("photos-clean.txt", "r") as f2: 
    count=0 
    for i in f2: 
     count = count + 1 
     cleaned = i.strip("\r\n") 
     transform = binascii.a2b_hex(cleaned) 
     with open("{}.jpg".format(count), 'wb') as output: 
      output.write(transform) 

回答

0

我想你有錯誤在線for i, data in (f2):。 你試圖從f2中解壓2個值和數據,我想你需要枚舉如下。 此外,我想你想使用我的索引文件名和寫,而不是數據變換成輸出

with open("photos-clean.txt", "r") as f2: 
    for i, data in enumerate(f2): 
     transform = binascii.a2b_hex(data) 
     with open('photo{}.jpg'.format(i), 'wb') as output: 
      output.write(transfrom) 
+0

謝謝你幫我。我已經改變了你的方式,它現在給我一個不同的錯誤:太多的值來解壓縮。任何想法可能是什麼?我已經刪除了枚舉,因爲我不想更改十六進制。 – Donald

+0

不清楚你想要什麼,枚舉不改變十六進制,沒有枚舉,你可以,噸得到我和數據,將有錯誤 – Skycc

+0

我希望文件中的每一行,這是一個十六進制,要轉換爲JPEG格式。我有70行,所以我想在我的文件夾中看到70個JPEG文件。我不知道它爲什麼獨立運作,但在一批中失敗。 – Donald