2016-11-08 132 views
0

我編寫了一個小密碼生成器,您可以將密碼及其服務保存在名爲「password.txt」的文件中。每次運行該程序時,該文件都保持空白。當我刪除文件並再次運行程序時,會創建文件「password.txt」,但仍然爲空。爲什麼Python不寫入文件?

import random 

letters = "1 2 3 4 5 6 7 8 9 Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m : ; , . 0".split() 

def checkNumb(string): 
    for i in string: 
     x = i.isdigit() 
     if x == True: 
      return True 

def createPassword(): 
    global letters 
    password = "" 
    i = 0 
    passLength = random.randint(7, 10) 
    while i < passLength: 
     passLetter = random.choice(letters) 
     password += passLetter 
     i += 1 
    x = checkNumb(password) 
    if x != True: 
     password = createPassword() 
    return password 

print("What is the name of the service?") 
service = input() 
password = createPassword() 
print(password, "will be your password for", service) 

file = open("password.txt","a") 
file.write(service + ": " + password) 
file.close() 

而且,因爲我是一個初學者,這將是一個很大的幫助,如果有人能指出一些改進,我可以在此代碼做。

編輯:while語句的縮進錯誤只是我在將代碼複製到這裏時犯的一個錯誤。該程序沒有縮進錯誤。謝謝asongtoruin提醒我。

+0

不知道這是抄襲的代碼SO,但你的縮進關 - '而我<通過朗:'應該符合上面的線。 – asongtoruin

+1

這個程序不會運行。你可以檢查縮進嗎?嚴重縮減的Python代碼是無稽之談。 – khelwood

+2

當我修復while循環的縮進後,我有一個'password.txt',其中包含所需的文本... –

回答

1

只是一個小缺口錯誤

import random 

letters = "1 2 3 4 5 6 7 8 9 Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m : ; , . 0".split() 

def checkNumb(string): 
    for i in string: 
     x = i.isdigit() 
     if x == True: 
      return True 

def createPassword(): 
    global letters 
    password = "" 
    i = 0 
    passLenght = random.randint(7, 10) 
    while i < passLenght: 
     passLetter = random.choice(letters) 
     password += passLetter 
     i += 1 
    x = checkNumb(password) 
    if x != True: 
     password = createPassword() 
    return password 

print("What is the name of the service?") 
service = input() 
password = createPassword() 
print(password, "will be your password for", service) 

file = open("password.txt","a") 
file.write(service + ": " + password) 
file.close() 

這工作,看的同時縮進createPassword()

輸出

python write_file.py 
What is the name of the service? 
service1 
SCawELnU7f will be your password for service1 

文件內容:

service1: uj.voSK38 

也r EFER此鏈接,文件追加差異

Opening a file for append

+0

縮進不在程序中。我無意中在將它寫在這裏的stackoverflow的編輯器中時添加了它。我編輯了我的帖子。對不起這是我的錯。 – user3162541

0

while i < passLenght:測試的代碼dedented一次,它的工作作爲inteneded