【问题标题】:Trying to change row2 on my csv file in python试图在python中更改我的csv文件的row2
【发布时间】:2020-09-24 22:53:56
【问题描述】:

所以我正在用 python 为学校构建一台 atm 机器。除了我想存/取钱时,一切都很好。我的循环只是将整个 csv 文件擦除干净,并且只有最新的条目存在。

所以我要做的是将我的 csv 复制到一个列表中,然后在右侧行中进行更改,然后将其写回 csv,并进行新的更改。

我真的被困在这里了.. =/ 但这是我的代码:

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

【问题讨论】:

  • 以追加模式打开文件:with open("accounts.csv", "a") as inf:
  • @Mike67 我可能是错的,但我认为如果他要替换现有值,那将行不通。
  • 追加将添加一个新行,而不是更改现有行 =/

标签: json python-3.x pandas csv


【解决方案1】:

无需深入研究代码,您的阅读器和编写器就会引用同一个文件。

  1. 如果将其写入不同的文件,是否可以接受?我会试试看。
  2. 如果你想要相同的文件名,我会在新文件完成后替换原始文件。

【讨论】:

    【解决方案2】:

    当用可以改变大小的数据结束一个文件时,你必须读入整个文件,改变数据,然后再次写出整个文件。当前代码只写回一行。

    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())
    

    测试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
    

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 2013-09-02
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多