gpt4 book ai didi

python - 选择哪种文件模式并循环创建列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:03 25 4
gpt4 key购买 nike

再次遇到另一个问题。我正在尝试制作一个“表格制作者” - 现在只是用字典创建文件并检查键。

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

最佳答案

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

x模式下,仅当文件已存在时才会创建,否则引发异常。 createTable 函数对我来说并没有真正的意义。 决策="is"然后如果决策=="is":决策应该是一个全局?非常模糊。

关于python - 选择哪种文件模式并循环创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com