Home > Software design >  Set CSV file's newline
Set CSV file's newline

Time:03-28

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

CodePudding user response:

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")
  • Related