我有一个重复试块问题

2024-09-29 06:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在这里做了一个小应用,我有try块(因为我需要看看一个文件是否已经存在或者应该被创建)。尽管。。。我的试块不知什么原因在重复!我完全不知道为什么会这样。请帮忙? 而且,文件创建得很好:) 代码:

import sys
import time
Version = "V0.1"
def user():
    PISBNdat = open("PISBN.dat", "w")
    PISBNdat.write(Version)
    cuser = raw_input("Please enter account username!")
    for line in PISBNdat:
        print "Test"
        if cuser in line:
            print("User already exists! Try again!")
            user()



def start():
    print "Hello and welcome to Plaz's PISBN!"
    print "Opening file..."
    time.sleep(0.8)
    try:
        fin = open("PISBN.dat", "r")
        print "Success!"
        fin.close()
        user()
    except:
        time.sleep(0.5)
        print "Did not recognize/find file!"
        time.sleep(0.1)
        print "Creating file!"
        time.sleep(0.5)
        try:
            fout = open("PISBN.dat", "w")
            print "Success!"
            fout.close()
            user()
        except:
            print "Failed!"
            exit()

start()

这是输出…:

Hello and welcome to Plaz's PISBN!
Opening file...
Did not recognize/find file!
Creating file!
Success!
Please enter account username! [This is what I entered: Plazmotech]
Failed!

很明显,既然上面写着“失败了!”,这意味着它运行我的试块。。。因为这是它唯一可以输出“Failed”的地方所以请帮帮我!你知道吗


Tags: importtimeversionsleepopendatfilesuccess
3条回答

下面是一个start()用法正确的try...except示例:

def start():
    print "Hello and welcome to Plaz's PISBN!"
    print "Opening file..."
    time.sleep(0.8)
    try: #try bloc contains minimum amount of code to catch the pertinent error.
        f = open("PISBN.dat", "r")
        print "Success!"
    except IOError: #Only catch the exceptions you want to handle. IOError, in this case
        f = None

    if not f:
        print "Did not recognize/find file!"
        print "Creating file!"

        try:
            f = open("PISBN.dat", "w")
            print "Success!"
        except IOError:
            print "Failed!"
            exit()

    f.close()
    user() #Call user() after the file has been tested and/or created.

正如之前有人(刚刚删除了他的帖子)指出的那样,在user函数中再次调用user(),这在这里很可能是错误的。你知道吗

不过,我相信你的问题出在别的地方。我想你想要“PISBN.dat公司“包含一个数据库,您可以在其中查找帐户。但是,仅以写权限打开文件将无助于此。这将导致您的循环“for line in PISBNdat:”根本不起作用,因此消息“Test”没有出现。你知道吗

这让我觉得“原始输入”失败,异常被捕获。但正如kindall指出的,您的代码有一些设计缺陷。你知道吗

只捕获要处理的异常。请注意,打印“失败!”退出是而不是处理异常。Python无论如何都会这么做,而且它会给您提供大量关于发生了什么的信息,所以为什么要编写额外的代码来做更少的工作并隐藏问题的原因呢?你知道吗

相关问题 更多 >