2017-04-16 49 views
0

我想寫隨機生成散列到一個文本,但每次在文本文件中沒有文字。我能做什麼? 這裏是我的代碼:Python中寫入一個文件

import hashlib 
import string 
from random import randint 
import random 
import time 

rnd = randint(10,20) 
while True: 
    rndChar = "" 
    for _ in range(rnd): 
     rndChar += random.choice(string.ascii_letters + string.digits) 
    md5out = hashlib.md5(rndChar).hexdigest() 
    float.fromhex('0.' + md5out[:16]) 
    float.fromhex('0.' + md5out[:16]) 
    print md5out 
    file = open('/home/testuser/Desktop/hash.txt', 'w') 
    file.write(str(md5out)) 
    file.close() 

控制檯輸出如下:

2720df62db5dd1881b011198280eb993 
283eafdd484385b4396c34df58936c85 
91aeb7daf22c53531b3f56b6d640a948 
784c7aaf8fe24148f4ffef7376951385 
49557f13c14a3022dbaae67f39d5af5e 
881a4744d9bbd996b2408fccff40f521 
21ff71063f55c91051b609ad40d31d7c 

所以它的工作原理,但在我的桌面上的文本文件未顯示。請幫助

回答

0

打開它file = open('/home/testuser/Desktop/hash.txt', 'a')爲「W」每次清除文本文件。

繼承人正確的代碼 進口hashlib 進口串 從隨機進口randint 進口隨機 進口時間

rnd = randint(10,20) 
while True: 
    rndChar = "" 
    for _ in range(rnd): 
     rndChar += random.choice(string.ascii_letters + string.digits) 
    md5out = hashlib.md5(rndChar).hexdigest() 
    float.fromhex('0.' + md5out[:16]) 
    float.fromhex('0.' + md5out[:16]) 
    print md5out 
    file = open('/home/testuser/Desktop/hash.txt', 'a') 
    file.write(str(md5out)) 
    file.close() 
+0

謝謝,我怎麼能寫在一個新行每個哈希? – SecDet

+0

沒問題 - 如果你發現它的工作/有助於請將它作爲一個答案/給予好評,因爲它確實幫助 - 不知道如何寫多lnes恐怕評論 – Monkeybike123

0

把while循環之外你打開文件,以及閉幕。每次打開它都會被清除。