2017-02-07 110 views
0

對於我正在做的任務,我需要破解一個鎖定的PDF文件。我正在嘗試創建一個密碼列表以便這樣做,但無法解決如何將此代碼生成的結果輸出到文本文件中。輸出到文本文件Python 2.7

from random import shuffle 
with open('randomwords.txt', 'r') as data: 
    data = data.read().split() 
    while(True): 
     shuffle(data) 
     password = '' 
     for x in data[:3]: 
      password += x 
     print password.replace('o','0') 

一切我已經試過到目前爲止還沒有工作,將不勝感激,如果有人能告訴我如何輸出的結果此代碼生成到外部文本文件。

變換溫控功能:

def transform(word): 
    from random import shuffle 
    with open('randomwords.txt', 'r') as data: 
      data = data.read().split() 
     while(True): 
       shuffle(data) 
       password = '' 
       for x in data[:3]: 
         password += x 
       print password.replace('o','0') 
    return word 
+0

那麼它好像你知道如何打開一個文件,所以以寫模式打開一個文件,而不是打印,寫入該文件。你也有一個無限循環,如果你正在寫一個文件,這會很糟糕... – MooingRawr

+0

http://www.pitt.edu/~naraehan/python2/reading_writing_methods.html –

+0

什麼結果需要寫入外部文件?你沒有任何結果 –

回答

0

您可能需要打開另外一個文件來寫你的輸出。

from random import shuffle 


def transform(word): 
    l = list(word) 
    shuffle(l) 
    new_word = ''.join(l) 
    return new_word[:3].replace('o', '0') 


input_file = 'randomwords.txt' 
output_file = 'passwords.txt' 
with open(input_file, 'r') as word_file: 
    with open(output_file, 'wb') as pwd_file: 
     for r in word_file: 
      word = r.strip() 
      password = transform(word) 
      pwd_file.write(password + '\n') 

參考:http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

+0

這類作品,但是當我查看它時,輸出文件是空的。 – Quarismo

+0

@Quarismo有趣。你能分享你的轉換功能嗎?我在randomwords.txt中放入了橙色\ ncolor \ n進行測試,並且工作正常。 – sangheestyle

+0

當然,我已將它添加到問題中。 – Quarismo