如何使用Python

时间:2016-01-20 16:38:33

标签: python csv filereader

我这里有一个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的数字?

由于

1 个答案:

答案 0 :(得分:0)

尝试一下:

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)

你经常调用它(例如在一个循环中)并不是很好。