如何操纵CSV数据?

时间:2016-05-29 18:46:47

标签: python python-2.7 csv row

我正在尝试制作一个银行程序,您现在可以选择在选择'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" 

1 个答案:

答案 0 :(得分:0)

替换文件中的值:

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)

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

  • 在#34; =="等运营商周围加入空格是一种更好的Python风格。和" =" (一个很好的资源:PEP-8
  • 如果您使用close()阻止,则不需要with您的文件。 with会自动关闭您的文件。
  • 您应该包含一些会破坏while循环的条件;否则它会无限循环。
  • 您的条件if声明错误。你想要这样的伪代码:if username exists: print "some message" else: open file and append line