所以,我正在写一个程序,用户从一堆卡片中取出一张。我将每堆卡片的数量写在一个文本文件中。该文件如下所示:
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]
。我该怎么做呢?
发布于 2017-04-19 04:43:25
pile = input("Which pile are you taking")
number = input("How many cards")
dict = {};
with open("cardfile.txt","r+") as file:
for line in file.readlines():
name,num = line.split(", ")
dict[name] = int(num)
if(name==pile):
found =1
oldnumber = int(num)
newnumber = oldnumber - int(number)
dict[name] =newnumber
out = open("cardfile.txt","w")
for d in dict:
out.write(d+", "+str(dict[d])+"\n")
out.close()
发布于 2017-04-19 05:15:21
然后,遍历这些行,找到与相关卡对应的行号以及要写入该行的新编号。最后,修改相关行对应的列表元素,将所有行写回文件:
pile = input("Which pile are you taking a card from?")
number = input("How many cards are you taking from this pile?")
# Prefer to use the with statement which closes the file for you
with open('cardfile.txt', 'rb') as f:
card_counts = f.readlines()
for i, card_count in enumerate(card_counts):
b = card_count.split(", ")
if b[0] == pile:
new_number = int(b[1]) - int(number)
line_position = i
break
card_counts[i] = str(b[0]) + ',' + str(new_number)
with open('cardfile.txt', 'wb') as wf:
wf.writelines(card_counts)
发布于 2017-04-19 04:39:20
不能用python编辑文本文件,只能追加、写入或读取文本。因此,在这种情况下,我会将新值存储在一个列表中,然后将它们重写到文本文件中。
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")
lines2write = []
for line in f.readlines():
b = line.split(",")
if b[0] == pile:
line = "{},{}\n".format(b[0], int(b[1])-int(number))
lines2write.append(line)
f.close()
# rewrite to the textfile
ftw = open("cardfile.txt", "w")
for line in lines2write:
ftw.write(line)
ftw.close()
https://stackoverflow.com/questions/43481462
复制相似问题