我正在嘗試創建一個銀行,但我無法更改文件的整數數據。 什麼我的文件中包含的是:如何處理CSV中的整數數據?
astle,hello,11
monish,mr7,0
在我的「選擇1」(在後面的代碼顯示),當我嘗試存入說假設100,它不會改變值,而不是給出了同樣的value.Like在
現在這種情況下,如果我輸入我的用戶名爲'astle'並嘗試存入100,則該值變爲100而不是111.我希望111當您存入時應該是舊值+新值。
我試過下面的代碼,但沒有用。
這是我的代碼:
import csv
run=True
while run==True:
print "1) Deposit money"
choice=input("Enter your choice over here: ")
#This part takes the input from the user and then stores it in 'store.txt'
if choice==1:
b=raw_input("Enter the username: ")
with open('store.txt','r') as f:
reader = list(csv.reader(f))
for row in reader:
if b==row[0]: #Check the username with the file
c=input("Enter your new ammount")
print row[2],"Old value"
a=int(row[2])
print a
row[2] = c
print row[2],"New value"
flag = 1
break
else:
flag=0
if flag==0:
print "Username does not exist."
#Writes the new value in the file
with open('store.txt','w') as f:
wr = csv.writer(f)
for row in reader:
wr.writerow(row)
我試圖與行替換行[2] = C [2] + = C,但它給了我下面的錯誤:
row[2]+=d
TypeError: cannot concatenate 'str' and 'int' objects
只需用'row [2] + = c'替換'row [2] = c'。但除了學術目的,一個CSV文件是**不是**這裏正確的工具;-) –
我沒有在您的代碼中看到'old value + newvalue'操作 – baf
@SergeBallesta我已經嘗試過,但它給了我這個錯誤。 TypeError:不能連接'str'和'int'對象。 –