如何解决Errno 2没有这样的文件或目录“即使只有一行代码,我仍然会收到此错误”
我只是从python开始,我想使用文本文件创建一个简单的登录系统。每次我运行代码时,都会出现此错误。它甚至不生成文本文件。在此之前,我可以运行我的代码并创建一个文件,但现在没有。我只尝试了一行代码来打开文本文件,但是那也不起作用。(代码行:f = open(“ demofile.txt”))我也试图用谷歌搜索它,没有解决办法。我不知道该怎么办?
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no,please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt",'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
f = open("dataBank.txt",'w')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt","r")
info = f.read()
info = info.split()
if name in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
解决方法
我不知道您的逻辑是什么,但是要创建文件,您需要使用w+
通过代码尝试
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no,please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
try:
f = open("dataBank.txt",'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
except:
return 'Data base donest exists. creating one...'
f = open("dataBank.txt",'w+')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt","r")
info = f.read()
info = info.split()
if username in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
,
您在f = open('demofile.txt')
中遇到的错误是因为open
附加了一个参数'mode',其默认值为'r'可供读取。如果传递的文件名不存在,则会得到描述的错误。
使用f = open('demofile.txt','w')
代替写入文件。如果文件名不存在,则会创建一个新文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。