在 csv 文件中写入新行 [重复]
Posted
技术标签:
【中文标题】在 csv 文件中写入新行 [重复]【英文标题】:Writing new lines in a csvFile [duplicate] 【发布时间】:2018-11-28 15:14:57 【问题描述】:我尝试创建一些代码来将新注册用户写入 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")
【问题讨论】:
不会按需要运行:reG = 'Username': userName, 'Surname': Surname, First Name': FirstName, 'Age': Age, 'YearGroup': YearGroup, 'passWord': passWord
【参考方案1】:
这里有一些调整可以让您的程序按预期工作:
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")
-
文件现在以追加模式而不是写入模式打开。
reG
现在是字典,符合 writerow 的要求。
仅当文件为空时才添加标头。
【讨论】:
以上是关于在 csv 文件中写入新行 [重复]的主要内容,如果未能解决你的问题,请参考以下文章