选择哪个文件模式并在循环中创建列表

2024-10-04 09:20:53 发布

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

又是一个问题。我正在尝试做一个“表生成器”——现在只是用字典和检查键创建文件

我有两个问题:首先,我不知道是否有一个文件格式可以写二进制文件,但如果以前的文件已经存在,就不能覆盖它?我尝试了(try,except)方法,但始终没有出现例外的FileExistsError:/(在createTable函数中)

其次,我在创建列表方面有问题。我做了一个循环,要求将条目和值存储在单独的列表中。这些列表稍后将被压缩到字典中,并整理成一个文件(在createTable函数中)

当然,如果还有其他的错误,我很乐意指出:)

import pickle

def checkTable(nameOfTable) :

    try :
        #seeing what is it they are looking for
        prompt = input("What do you want to check?\n")
        with open("%s.pkl" % nameOfTable, "rb") as f:
            data = pickle.load(f)
            #getting what they want from the data from table
            whatTheyWant = data.get(prompt, "There is nothing like that in the table.\n")
            print(whatTheyWant)
    #if table doesn't exist
    except IOError as e:
        print("Sorry such a directory doesn't exist.\n")


def createTable(nameOfYourTable) :
    try :
        #opens a new file with the table
        with open("%s.pkl" %nameOfYourTable, "wb+") as f :
            decision = "yes"
            if decision == "yes" :
                #asking for entries and keys to put into the table
                #creates lists with entries and values to be zipped together
                entry.append = input("What is the entry?\n")
                value.append = input("What is the value of the entry?\n")
                decision = input("Do you want to go on? (yes/no)\n")
                i += 1
            else :
            #getting it all into a dictionary and putting it into a file
                table={dict(zip(entry, value))}
                pickle.dump(table, f)
    #if a file with the name already exists
    except FileExistsError as e :
        print("Sorry, a file with this name already exists.")


#what the person wants to do
answer = input("Hello. Do you want to create a table or check an existing one?\n")

#asking for the name of the new table
if answer == "create" :
    nameOfYourTable = input("What do you want the table to be called?\n")
    createTable(nameOfYourTable)
#asking what table to look in
elif answer == "check" :
    nameOfTable = input("What is the name of the table?\n")
    checkTable(nameOfTable)
else :
    print("\nThat's not a valid option.\n")

print("Thank you for using me. It was very nice.")

Tags: 文件thetoyouforinputiswith
2条回答

有一个文件模式只为您想要的,open(file, "x"),添加bt根据您的需要

x模式下,仅当文件已存在时才创建文件,否则会引发异常。createTable函数对我来说真的没有意义^{<然后if decision == "yes":decision应该是global?很模糊

首先需要pickle从文件中读取列表,添加到列表中,然后在最后编写一个新的pickle文件。顺便说一句,您可以用os.path.exists检查文件是否存在。用list_name.append(new_item)将项追加到列表中。您需要先用list_name = []初始化列表

相关问题 更多 >