无法让新的线路在python中工作?

时间:2014-01-19 17:34:43

标签: python windows python-3.x

这是我正在尝试获取新行的代码。可悲的是,它只是重写了该计划的第一行。到底是怎么回事?如果你能帮到我,我将非常感激。

import itertools
import string
import sys, os, cmd

from datetime import datetime
FMT = '%Y-%m-%d %H:%M:%S'
passwordstried = 0


numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0',]
symbols = ["!","@","#","$","%","^","&","*","(",")","_","-","'",'"',":",";","+","=","[","{","]","}","<",",",">",".","?","/","|","\"","~","`"]
lowercaseletters = ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","g","h","j","k","l","z","x","c","v","b","n","m"]
uppercaseletters = ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","G","H","J","K","L","Z","X","C","V","B","N","M"]


stuff = lowercaseletters + uppercaseletters + numbers + symbols


if (input("Do you have the length of the password?") == 'y'):
    lengthstartingvalue = int(input("Password length: "))
else:
    lengthstartingvalue = 1


starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(starttime)


starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
for L in range(lengthstartingvalue, len(stuff)+1):
    for subset in itertools.combinations_with_replacement(stuff, L):
        #print(subset)


        password = ''.join(subset)
        print(password)

        file = open("generatedpasswords.txt","w")
        file.write(str(password) + '\n')

        passwordstried = passwordstried + 1
    if (L>lengthstartingvalue+1):
        break

endtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
elapsed = datetime.strptime(endtime, FMT) - datetime.strptime(starttime, FMT)
print ('Time elapsed:',elapsed)
print ('Passwords tried:',passwordstried)
file.close()

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您在循环内重新打开相同的文件...

file = open("generatedpasswords.txt","w")
for L in range(lengthstartingvalue, len(stuff)+1):
    for subset in itertools.combinations_with_replacement(stuff, L):
        #print(subset)


        password = ''.join(subset)
        print(password)


        file.write(str(password) + '\n')




        passwordstried = passwordstried + 1
    if (L>lengthstartingvalue+1):
        break

这将一次又一次地重新打开同一个文件,并最终将最后一个密码写入文件中 如果您想要附加当前密码并且不想丢失以前的数据,那么您可以在for循环中使用file = open("generatedpasswords.txt","a") ....