如何在fi上重写

2024-10-09 03:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我在写一个程序,用户从一堆卡片中取出一张卡片。我把每一堆卡片的数量写在一个文本文件里。文件如下所示:

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]。我该怎么做?你知道吗


Tags: 用户from程序younumberinputlineare
3条回答

您可以首先获取文件中的所有行并关闭文件。然后,遍历这些行以找到对应于相关卡的行号以及要写入该行的新编号。最后,修改与相关行对应的列表元素,并将所有行写回文件:

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)
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()

不能用python编辑文本文件,只能附加、写入或读取文本。所以在本例中,我将把新值存储在一个列表中,然后在之后将它们重写到textfile。你知道吗

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()

相关问题 更多 >

    热门问题