如何使用Python更改CSV中的单个值

2024-06-28 20:50:30 发布

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

这里有一个CSV文件:

123456789,Football,100,19
123456789,TennisRacket,120,35

使用Python,每次用户想要购买一个网球拍时,如何将第二行的数字35(网球拍的数量)更改为-1?这是我的密码:

areyousure = input("Are you sure you want to purchase? Y/N")
    areyousure = areyousure.upper()
if areyousure == "Y":
    itemfile = open("Bought items.text","w")

每次用户键入“Y”时,数字35都会减少1,我可以在这个代码下面加什么?你知道吗

谢谢


Tags: 文件csv用户you密码input数量数字
1条回答
网友
1楼 · 发布于 2024-06-28 20:50:30

下面是一个尝试:

import csv    

areyousure = input("Are you sure you want to purchase? Y/N")
    areyousure = areyousure.upper()
if areyousure == "Y":
    itemfile = open("Bought items.text","w")

    # Create a Python array from your csv
    with open('/yourCSVfile.csv', 'rb') as f:
        reader = csv.reader(f)
        r = list(reader)

    r[1][3] -= 1 # access 35 in the new array, subtract 1

    # Overwrite your csv with the modified Python array
    with open("yourCSVfile.csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerows(r)

如果您经常调用它(例如在循环中),那就不太好了。你知道吗

相关问题 更多 >