为什么Python不写入文件?
问题描述:
我编写了一个小密码生成器,您可以将密码及其服务保存在名为“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提醒我。
答
只是一个小缺口错误
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此链接,文件追加差异
+0
缩进不在程序中。我无意中在将它写在这里的stackoverflow的编辑器中时添加了它。我编辑了我的帖子。对不起这是我的错。 – user3162541
答
与while i < passLenght:
测试的代码dedented一次,它的工作作为inteneded
不知道这是抄袭的代码SO,但你的缩进关 - '而我 asongtoruin
这个程序不会运行。你可以检查缩进吗?严重缩减的Python代码是无稽之谈。 – khelwood
当我修复while循环的缩进后,我有一个'password.txt',其中包含所需的文本... –