在关闭程序之前添加文件后如何从 file.txt 中检索信息
Posted
技术标签:
【中文标题】在关闭程序之前添加文件后如何从 file.txt 中检索信息【英文标题】:How can I retrieve information from a file.txt after adding it before turning off the program 【发布时间】:2020-07-10 16:48:56 【问题描述】:我正在学习生成 .txt 文件以及如何编写和读取它们,我现在遇到的问题是我想制作一个程序,我可以在其中创建、编辑和删除看起来类似于表格的字符和这些新字符保存在file.txt中
看到角色有共同的属性,我考虑使用类,我不是这方面的专家,但我知道一点,我的主要想法是要求属性并生成一个对象并添加它到一个字符列表,这样做一切都很好,但是当你再次启动程序时数据不会保存
class PLAYER:
def __init__(self,Name,Attack,Defense,Health):
self.Name=Name
self.Attack=Attack
self.Defense=Defense
self.Health=Health
options=[0,1,2,3]
characters=[]
while True:
counter=0
archive = open("players.txt","w")
print("ID|NAME|ATTACK|DEFENSE|HEALTH")
while counter != len(characters):
print("(",counter,")", characters[0+counter].Name,characters[0+counter].Attack,characters[0+counter].Defense,characters[0+counter].Health)
counter += 1
print("Character Manager")
print("( 0 ) Create")
print("( 1 ) Edit")
print("( 2 ) Delete")
print("( 3 ) Exit")
while True:#Choose the option
try:
option=int(input("-> "))
while option not in options:
print("Are you looking to find more options? Sorry, friend, there is no budget for that")
option=int(input("-> "))
break
except ValueError:
print("Please write the number in parentheses of the option you want to do")
if option==3:#Exit
archive.close()
break
elif option==0:#Crear
NAME=input("What will his name be? ")
while True:#Ataque
try:
ATTACK=int(input("How much attack will it have? "))
break
except:
print("please put an integer value")
while True:#Defensa
try:
DEFENSE=input("How much will your defense be? ")
break
except:
print("please put an integer value")
while True:#Vida
try:
HEALTH=input("How much life will it have?")
break
except:
print("please put an integer value")
characters.append(PLAYER(NAME,ATTACK,DEFENSE,HEALTH))
elif option==1:#Edit
print("Which character do you want to edit?")
ID=int(input("-> "))
characters.remove(characters[ID])
NAME=input("What will be his new name? ")
while True:#Ataque
try:
ATTACK=int(input("How much attack will it have? "))
break
except:
print("please put an integer value")
while True:#Defensa
try:
DEFENSE=input("How much will your defense be?")
break
except:
print("please put an integer value")
while True:#Vida
try:
HEALTH=input("How much life will it have?")
break
except:
print("please put an integer value")
characters.append(PLAYER(NAME,ATTACK,DEFENSE,HEALTH))
elif option==2:#Delete
print("¿Qué personaje quieres eliminar?")
ID=int(input("-> "))
characters.remove(characters[ID])
到目前为止我还没有使用.txt文件,为了不再显示完整的代码,我将只放改变的部分
counter=0
archive = open("players.txt","w")
print("ID|NAME|ATTACK|DEFENSE|HEALTH")
while counter != len(characters):
a=("(",counter,")", characters[0+counter].Name,characters[0+counter].Attack,characters[0+counter].Defense,characters[0+counter].Health)
archive.write(a)
archive.write("\n")
counter += 1
archive.close()
archive = open("personajes.txt","r")
print(archive.read())
print("Character Manager")
print("( 0 ) Create")
print("( 1 ) Edit")
print("( 2 ) Delete")
print("( 3 ) Exit")
我这里发现的问题是write参数必须是str,不是tuple而是放的时候
a = str ("all the stuff")
在我看来
TypeError: str() takes at most 3 arguments (7 given)
所以现在我没有找到解决方法的想法,我希望你能帮助我解决这个问题,因为我自己找不到解决方案
我正在寻找的一个例子是这样的
ID|NAME|ATTACK|DEFENSE|HEALTH
Character Manager
( 0 ) Create
( 1 ) Edit
( 2 ) Delete
( 3 ) Exit
-> 0
What will his name be? Joseph
How much attack will it have? 20
How much will your defense be? 10
How much life will it have?50
ID|NAME|ATTACK|DEFENSE|HEALTH
( 0 ) Joseph 20 10 50
Character Manager
( 0 ) Create
( 1 ) Edit
( 2 ) Delete
( 3 ) Exit
但我希望当我开始时,如果有旧的注册字符会出现
如果我使用 f 字符串
counter=0
archive = open("players.txt","w")
print("ID|NAME|ATTACK|DEFENSE|HEALTH")
while counter != len(characters):
a=f"( counter ) characters[counter].Name characters[counter].Attack characters[counter].Defense characters[counter].Health"
archive.write(a)
archive.write("\n")
counter += 1
archive.close()
archive = open("personajes.txt","r")
print(archive.read())
新字符被打印,但在关闭程序并重新打开之前创建的字符消失时
【问题讨论】:
您能否展示一个示例输入和您正在寻找的输出 您可以让类覆盖__str__
和 __repr__
。或者使用 f 字符串:a=f"( counter ),characters[counter].Name characters[counter].Attack characters[counter].Defense characters[counter].Health"
我刚刚编辑了问题以显示我正在寻找的输出类型
使用 f-string 打印新字符,但在关闭程序并重新打开它时没有字符出现
使用pickle 将对象存储(序列化)到磁盘并检索(反序列化)它们。
【参考方案1】:
使用列表推导将所有行创建为字符串,然后使用 join 将它们全部与 \n
info = '\n'.join([list comprehension here])
file.write(info)
【讨论】:
【参考方案2】:您可以使用pickle 将对象存储和检索到磁盘。这是基于您的代码的示例:
import pickle
class Player:
def __init__(self, name, attack, defense, health):
self.name = name
self.attack = attack
self.defense = defense
self.health = health
def __str__(self):
return f"self.name self.attack self.defense self.health"
# Create 2 objects and save
def create_and_save():
p1 = Player("name1", 1, 2, 3)
p2 = Player("name2", 4, 5, 6)
with open("players.bin", "wb") as f:
pickle.dump(p1, f)
pickle.dump(p2, f)
# Load the previously store object and print them
def load_data():
with open("players.bin", "rb") as f:
p1 = pickle.load(f)
p2 = pickle.load(f)
print(p1)
print(p2)
choice = int(input("1. Save, 2. Load: "))
if choice == 1:
create_and_save()
else:
load_data()
运行程序两次。第一次输入“1”,第二次输入“2”。
附注我已经修改了类成员名称以适应 pep guide。
【讨论】:
以上是关于在关闭程序之前添加文件后如何从 file.txt 中检索信息的主要内容,如果未能解决你的问题,请参考以下文章