为什么要覆盖用户在我的csv文件中输入的先前数据?

时间:2017-10-09 21:04:55

标签: python python-3.x csv

这是我的代码:

class CSV:
    def __init__(self, path, hdrs):
    self.path = path  # raw string path; i.e. using r"/path/to/file"
    self.headers = hdrs  # list of strings ['Username', 'Password']
    self.created = False

    def create(self):
        with open(self.path, 'w', newline='') as f:
            w = csv.writer(f, delimiter=',')
            w.writerow(self.headers)
        self.created = True
        return self.headers

    def read(self):
        with open(self.path, 'r', newline='') as f:
            r = csv.reader(f, delimiter=',')
            rows = list(r)
        return rows

    def write(self, data):  # list of strings ['Username', 'Password']
        if not self.created:
            rows = [self.create()]  # create list of lists
        else:
            rows = self.read()  # this is a list of lists by default
        rows.append(data)
        with open(self.path, 'w', newline='') as f:
            w = csv.writer(f, delimiter=',')
            w.writerows(rows)

def register():
    print ("Your username will now be created from your first name and age.")
    fname = input("Please enter your first name: ")
    age = input("Please enter your age: ")
    fname2 = fname[:3]
    username = fname2 + age
    print ("Your username is {}".format(username.upper()))
    password = input("Please enter a password for your new account: ")

    time.sleep(1.0)

    print ("Username: {}".format(username))
    print ("Password: {}".format(password))



    myCSV = CSV('/Users/Sidd/Desktop/python/Coursework/UserPass.csv', ['Username', 'Password'])
    new = [username, password]
    myCSV.write(new)

在第一个代码块中,它在我的csv文件中创建了Username和Password标头。

在第二个代码块中,它将用户的用户名和密码写入标题下方的csv文件中。但是当另一个用户输入另一个用户名和密码时,它会覆盖以前的用户名和密码,而不是低于csv文件中的先前用户名和密码

我该如何解决这个问题? 谢谢。

1 个答案:

答案 0 :(得分:1)

它会覆盖它,因为每次新用户出现时都会调用第一个with

我不是文件I / O上'a'方法的忠实粉丝。我看到过多的读/写损坏。相反,为什么不呢:

  • 仅创建一次文档(因此请忽略再次调用DictWriter
  • 阅读内容并存储
  • 附加新内容并覆盖

在我的Python 3.6.2上测试一下吧! (减去'/path/to/file'

import csv

class CSV:
    def __init__(self, path, hdrs):
        self.path = path # raw string path; i.e. using r"/path/to/file"
        self.headers = hdrs # list of strings ['Username', 'Password']
        self.created = False

    def create(self):
        with open(self.path, 'w', newline = '') as f:
            w = csv.writer(f, delimiter = ',')
            w.writerow(self.headers)
        self.created = True
        return self.headers

    def read(self):
        with open(self.path, 'r', newline = '') as f:
            r = csv.reader(f, delimiter = ',')
            rows = list(r)
        return rows

    def write(self, data): # list of strings ['Username', 'Password']
        if not self.created:
            rows = [self.create()] # create list of lists
        else:
            rows = self.read() # this is a list of lists by default
        rows.append(data)
        with open(self.path, 'w', newline = '') as f:
            w = csv.writer(f, delimiter = ',')
            w.writerows(rows)

def register(fin):
    print ("Your username will now be created from your first name and age.")
    name = input("Please enter your first name: ")
    age = input("Please enter your age: ")
    name2 = name[:3].upper()
    username = name2 + age
    print ("Your username is", username)
    password = input("Please enter a password for your new account: ")

    time.sleep(1.0)

    print ("Username:", username)
    print ("Password:", password)

    fin.write([username, password])

myCSV = CSV('/path/to/file', ['Username', 'Password'])
register(myCSV) # fill in with some values
register(myCSV) # fill in with some newer values