Json 尝试在python中更改csv文件的第2行
所以我正在用python为学校构建一台atm机。除了我想存/取钱的时候,一切都很好。我的循环只是将整个csv文件擦除干净,只有最新的条目存在 所以我要做的是将我的csv复制到一个列表中,然后在右边的行中进行更改,然后用新的更改将其写回csv 我真的被困在这里了但我的密码是:Json 尝试在python中更改csv文件的第2行,json,python-3.x,pandas,csv,Json,Python 3.x,Pandas,Csv,所以我正在用python为学校构建一台atm机。除了我想存/取钱的时候,一切都很好。我的循环只是将整个csv文件擦除干净,只有最新的条目存在 所以我要做的是将我的csv复制到一个列表中,然后在右边的行中进行更改,然后用新的更改将其写回csv 我真的被困在这里了但我的密码是: def changeBalance(username): with open("accounts.csv") as inf: reader = csv.reader(inf.re
def changeBalance(username):
with open("accounts.csv") as inf:
reader = csv.reader(inf.readlines())
with open("accounts.csv", "w") as inf:
amount = input("Ange belopp: ₹ ")
writer = csv.writer(inf)
for line in reader:
if line[0] == username:
newBalance = str(float(line[2]) + float(amount))
line[2] = newBalance
writer.writerow(line)
print("\nInsatt summa: ₹",(amount) ,(today), (nowTime))
print (f"Aktuellt saldo: ₹ {newBalance}")
break
如果不深入查看代码,您的读写器将引用同一个文件
当用可能改变大小的数据结束文件时,必须读入整个文件,更改数据,然后再次写出整个文件。当前代码只回写一行
import csv
def changeBalance(username):
# read all the lines
with open('accounts.csv', 'r', newline='') as inf:
lines = list(csv.reader(inf))
with open('accounts.csv', 'w', newline='') as outf:
amount = float(input('Ange belopp: ₹ '))
writer = csv.writer(outf)
# process lines
for line in lines:
if line[0] == username: # change the amount for just this line
line[2] = float(line[2]) + amount
print(f'\nInsatt summa: ₹ {amount}')
print(f'Aktuellt saldo: ₹ {line[2]}')
writer.writerow(line) # but write every line out
changeBalance('user1')
changeBalance('user2')
with open('accounts.csv') as f:
print(f.read())
Test accounts.csv:
user1,col2,100.0,col3,col4
user2,col2,200.0,col3,col4
输出:
Ange belopp: ₹ 5
Insatt summa: ₹ 5.0
Aktuellt saldo: ₹ 105.0
Ange belopp: ₹ 7
Insatt summa: ₹ 7.0
Aktuellt saldo: ₹ 207.0
user1,col2,105.0,col3,col4
user2,col2,207.0,col3,col4
在追加模式下打开文件:
,以Open(“accounts.csv”,“a”)作为inf:
@Mike67我可能错了,但如果他替换现有值,我认为这不起作用。追加将添加新行,而不是更改现有行=/