[英]Ouput to text file Python 2.7
對於我正在做的作業,我需要破解一個鎖定的PDF文件。 我正在嘗試創建一個密碼列表,但是卻無法解決如何將此代碼產生的結果輸出到文本文件中。
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
您可能需要打開另一個文件來寫入輸出。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.