在csvFile中写入新行

时间:2018-06-19 15:31:40

标签: python csv writer

我尝试创建一些代码以将新的注册用户写入CSV文件。它正在替换文件中的现有用户。现在,它没有输入任何数据。我不确定哪里出了问题。

这是代码:

FirstName = input("Enter your  first name: ")
Surname = input("Enter your surname: ")
Age = input("Enter your age: ")
YearGroup = input("Enter your year group: ")
userName = input("Create a unique username: ")
passWord = input("Create a password: ")
fieldnames =['Username', 'Surname', 'First Name', 'Age', 'YearGroup', 'passWord']
reG = [{'Username': userName, 'Surname': Surname, 'First Name': FirstName,
                    'Age': Age, 'YearGroup': YearGroup, 'passWord': passWord}]
with open('StudentUserName.csv', 'w', newline='\n') as csvUser:
    reG = [{'Username': userName, 'Surname': Surname, 'First Name': FirstName,
                    'Age': Age, 'YearGroup': YearGroup, 'passWord': passWord}]
    writer = csv.DictWriter(csvUser, fieldnames)
    #writer.seek(0,2)
    writer.writeheader()
    writer.writerow(reG)

    #writer.writerow("\r")
    #writer.writerow({userName, Surname, FirstName,
    #                 Age, YearGroup, passWord})
csvUser.close()
print ("Registration completed")

2 个答案:

答案 0 :(得分:0)

您正在使用w(写入模式)打开文件:

  

以csvUser的身份打开('StudentUserName.csv',' w ',newline ='\ n'):

要添加新行(附加),您需要以附加模式“ a”打开文件。因此将是:

  

以csvUser的身份打开('StudentUserName.csv',' a ',newline ='\ n'):

可能希望阅读以下内容:https://docs.python.org/3.4/library/fileformats.html

答案 1 :(得分:0)

这里有一些调整可以使您的程序按预期工作:

import csv
import os

FirstName = input("Enter your  first name: ")
Surname = input("Enter your surname: ")
Age = input("Enter your age: ")
YearGroup = input("Enter your year group: ")
userName = input("Create a unique username: ")
passWord = input("Create a password: ")

fieldnames = ['Username', 'Surname', 'First Name', 'Age', 'YearGroup', 'passWord']

filename = 'StudentUserName.csv'

# The file is now opened in append mode instead of write mode.
with open(filename, 'a', newline='\n') as csvUser:

    # reG is now a dictionary, as required by writerow.
    reG = {'Username': userName, 'Surname': Surname, 'First Name': FirstName,
           'Age': Age, 'YearGroup': YearGroup, 'passWord': passWord}

    writer = csv.DictWriter(csvUser, fieldnames=fieldnames)

    # if it's an empty file, write the header
    if os.stat(filename).st_size == 0:
        writer.writeheader()

    writer.writerow(reG)

    # writer.writerow("\r")
    # writer.writerow({userName, Surname, FirstName,
    #                 Age, YearGroup, passWord})
csvUser.close()
print ("Registration completed")
  1. 该文件现在以附加模式而不是写入模式打开。
  2. reG现在是字典,符合writerow的要求。
  3. 仅当文件为空时才添加标题。