首页 > 解决方案 > 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())

标签: pythontext-files

解决方案


我不知道你的逻辑是什么,但要创建一个文件,你需要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())

推荐阅读