[英]How to manipulate integer data in CSV?
我正在嘗試建立一個銀行,但是我無法更改文件的整數數據。 我的文件包含以下內容:
astle,hello,11
monish,mr7,0
現在在我的``choice1''中(稍后在代碼中顯示),當我嘗試存入假設100時,它不會更改值,而是給出相同的值。在這種情況下,如果我輸入用戶名作為``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)
我嘗試用row [2] + = c替換row [2] = c,但是它給了我以下錯誤:
row[2]+=d
TypeError: cannot concatenate 'str' and 'int' objects
您需要將值從str
轉換為int
。 嘗試這個。
row[2] = str(int(row[2]) + c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.