设置 CSV 文件的换行符
当我写入 csv 文件时,我试图创建一个换行符,但它一直给我一个错误“ValueError:非法换行符值:”。我尝试用“a”替换“w”。
import csv
number = input("Enter student count: ")
jada = 1
for i in number:
student = input("Student name: ")
value = input("Enter the deposited amount: ")
with open('budget.csv', 'w', newline=' \n', encoding = 'utf-8') as file:
write = csv.writer(file)
writer.writerow(["Nmr", "Name", "Deposited amount"])
writer.writerow([jada, student, value])
jada += 1
I'm trying to create a newline when I write to a csv file, but it keeps giving me an error 'ValueError: illegal newline value: '. I've tried replacing 'w' with 'a'.
import csv
number = input("Enter student count: ")
jada = 1
for i in number:
student = input("Student name: ")
value = input("Enter the deposited amount: ")
with open('budget.csv', 'w', newline=' \n', encoding = 'utf-8') as file:
write = csv.writer(file)
writer.writerow(["Nmr", "Name", "Deposited amount"])
writer.writerow([jada, student, value])
jada += 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您收到
ValueError: invalid newline value:
因为您的换行符开头有一个空格,\n
。但如果你试图强制执行特定的换行符,那不会有任何效果。您需要使用
lineterminator
^创建编写器时的 1 选项:CSV 文档特别建议使用
newline=""
^2:因此您的代码应如下所示:
You are getting
ValueError: illegal newline value:
because your newline has a space at the beginning,\n
.But if you're trying to force a particular newline, that won't have any effect. You need to use the
lineterminator
^1 option when creating the writer:And the CSV docs specifically recommend using
newline=""
^2:So your code should look more like this: