python – How to write to a CSV line by line?

python – How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open(csvfile.csv,wb) as file:
    for line in text:
        file.write(line)
        file.write(n)

OR

Using CSV writer :

import csv
with open(<path to output_csv>, wb) as csv_file:
        writer = csv.writer(csv_file, delimiter=,)
        for line in data:
            writer.writerow(line)

OR

Simplest way:

f = open(csvfile.csv,w)
f.write(hi theren) #Give your csv text here.
## Python will convert n to os.linesep
f.close()

You could just write to the file as you would write any normal file.

with open(csvfile.csv,wb) as file:
    for l in text:
        file.write(l)
        file.write(n)

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open(csvfile.csv, wb) as file:
    writer = csv.writer(file)
    writer.writerows(text)

python – How to write to a CSV line by line?

I would simply write each line to a file, since its already in a CSV format:

write_file = output.csv
with open(write_file, wt, encoding=utf-8) as output:
    for line in text:
        output.write(line + n)

I cant recall how to write lines with line-breaks at the moment, though :p

Also, you might like to take a look at this answer about write(), writelines(), and n.

Leave a Reply

Your email address will not be published. Required fields are marked *