【问题标题】:How to manipulate CSV data?如何操作 CSV 数据?
【发布时间】:2016-05-29 18:46:47
【问题描述】:

我正在尝试制作一个银行程序,您现在可以选择更改选项“2”中的密码。我尝试这样做但无济于事。谁能告诉我如何更改密码存储在“store.txt”的第 2 行。
示例:
这是我存储在文件“store.txt”中的数据

hello,me,0
bye,you,0

我要做的是将用户名“hello”的密码更改为“yolo”。我该怎么做?
这是我的代码:

import csv
run=True
while run==True:
    print "1)Create a new account"
    print "2) Change Password"
    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:
        a=input("Enter how many people to register: ")
        for i in range(0,a) :
            #Stores username and password
            a=raw_input("Enter username: ")
            b=raw_input("Enter password: ")
            c=0
            #If username already exists, stop the process.
            with open ('store.txt','r') as store:
                reader = csv.reader(store)
                for row in reader:
                    if a==row[0]:
                        print "User already exists in our database , please try again."
                        break
            store.close()
            #If username is not there , write it down to store.txt
            with open ('store.txt','a') as store:
                storeWriter=csv.writer(store)
                storeWriter.writerow([a,b,c])
            store.close()

    if choice==2:
        print "Change password" 

【问题讨论】:

    标签: python python-2.7 csv row


    【解决方案1】:

    要替换文件中的值:

    with open('store.txt','r') as f:
        reader = list(csv.reader(f))
        for row in reader:
            row[1] = "some-new-value"
    
    with open('store.txt','w') as f:
        wr = csv.writer(f)
        for row in reader:
            wr.writerow(row)
    

    还有很多方法可以改进你的代码:

    • 在“==”和“=”等运算符周围包含空格会更好(一个很好的资源:@​​987654321@)
    • 如果您使用with 块,则不需要close() 您的文件。 with 会自动关闭您的文件。
    • 您应该包含一些会破坏while 循环的条件;否则它将无限循环。
    • 您的条件if 语句是错误的。你想要这样的伪代码:if username exists: print "some message" else: open file and append line

    【讨论】:

    • 当我使用您的代码时,我收到一条错误消息 >AttributeError: 'file' object has no attribute 'writerow' 我尝试将其更改为 'write' 并且它有效,但后来我的文件我清除了,也就是说没有数据。
    • 很抱歉 - 修正了错字。我的答案中的代码肯定对你有用。如果您有任何其他问题,请告诉我。
    • 我的荣幸!祝你好运-
    猜你喜欢
    • 2016-08-02
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2023-03-07
    • 2021-01-21
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多