2016-01-20 44 views
0

在这里,我有一个CSV文件,以改变在CSV单个值:如何使用Python

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的数字35吗?

感谢

+2

我想你需要把csv读入数组,编辑然后写一个新的csv。 – Rodolphe

回答

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) 

这将不会是很大的,你经常把它(在例如一个循环)。

+0

谢谢,很快就会试用! –