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

时间:2016-04-03 20:34:35

标签: python list file python-3.x dictionary

又回来了另一个问题。我正在努力打造一个桌面制造商" - 现在只需创建带字典和检查键的文件。

我有两个问题:首先我不知道是否存在用于写入二进制文件的文件格式,但是如果它已经存在则不会覆盖以前的文件?我尝试了(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.")

2 个答案:

答案 0 :(得分:1)

根据您的需要,您可以根据需要设置文件模式,open(file, "x"),添加bt

x模式下,只有 时才会创建文件,否则会引发异常。 createTable函数对我来说没有意义。 decision = "yes"然后if decision == "yes":decision应该是global?这很模糊。

答案 1 :(得分:0)

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