设置 CSV 文件的换行符
Set CSV file's newline
我试图在写入 csv 文件时创建一个换行符,但它一直给我一个错误 'ValueError: illegal newline value: '。我试过用 '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
你得到 ValueError: illegal newline value:
因为你的换行符开头有一个 space, \n
.
但是如果您试图强制换行,那将不会有任何效果。创建writer时需要使用lineterminator
^1选项:
writer = csv.writer(file, lineterminator="\n")
CSV 文档特别推荐使用 newline=""
^2:
If csvfile is a file object, it should be opened with newline=''
因此您的代码应该更像这样:
with open("budget.csv", "w", newline="") as file:
writer = csv.writer(file, lineterminator="\n")
我试图在写入 csv 文件时创建一个换行符,但它一直给我一个错误 'ValueError: illegal newline value: '。我试过用 '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
你得到 ValueError: illegal newline value:
因为你的换行符开头有一个 space, \n
.
但是如果您试图强制换行,那将不会有任何效果。创建writer时需要使用lineterminator
^1选项:
writer = csv.writer(file, lineterminator="\n")
CSV 文档特别推荐使用 newline=""
^2:
If csvfile is a file object, it should be opened with
newline=''
因此您的代码应该更像这样:
with open("budget.csv", "w", newline="") as file:
writer = csv.writer(file, lineterminator="\n")