设置 CSV 文件的换行符

发布于 2025-01-16 21:50:55 字数 507 浏览 0 评论 0原文

当我写入 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦与时光遇 2025-01-23 21:50:55

您收到 ValueError: invalid newline value: 因为您的换行符开头有一个空格,\n

但如果你试图强制执行特定的换行符,那不会有任何效果。您需要使用 lineterminator^创建编写器时的 1 选项:

writer = csv.writer(file, lineterminator="\n")

CSV 文档特别建议使用 newline=""^2

如果 csvfile 是文件对象,则应使用 newline='' 打开它

因此您的代码应如下所示:

with open("budget.csv", "w", newline="") as file:
    writer = csv.writer(file, lineterminator="\n")

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:

writer = csv.writer(file, lineterminator="\n")

And the CSV docs specifically recommend using newline=""^2:

If csvfile is a file object, it should be opened with newline=''

So your code should look more like this:

with open("budget.csv", "w", newline="") as file:
    writer = csv.writer(file, lineterminator="\n")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文