所以,我在写一个程序,用户从一堆卡片中取出一张卡片。我把每一堆卡片的数量写在一个文本文件里。文件如下所示:
A, 10
B, 9
C, 7
D, 8
共有4个牌堆,A、B、C、D。逗号将牌堆名称与牌堆中的牌数分开。当用户输入要从中取出一张牌的牌堆,然后输入要从中取出多少张牌时,我希望程序在用户取出牌堆后,将该牌堆中的牌数重写为该牌堆中的牌数。例如,用户从B堆中取出3张卡,所以我希望程序自动将B堆中的9张卡更改为9-3=6张。你知道吗
这是我写的代码:
pile = input("Which pile are you taking a card from?")
number = input("How many cards are you taking from this pile?")
f = open("cardfile.txt", "r+")
found = 0
for line in f.readlines():
b = line.split(", ")
if (b[0])==pile):
found = 1
oldnumber = int(b[1])
newnumber = oldnumber - int(number)
我想用变量newnumber
的值替换文本文件中的b[1]
。我该怎么做?你知道吗
您可以首先获取文件中的所有行并关闭文件。然后,遍历这些行以找到对应于相关卡的行号以及要写入该行的新编号。最后,修改与相关行对应的列表元素,并将所有行写回文件:
不能用python编辑文本文件,只能附加、写入或读取文本。所以在本例中,我将把新值存储在一个列表中,然后在之后将它们重写到textfile。你知道吗
相关问题 更多 >
编程相关推荐