close

How to write to a CSV line by line?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to write to a CSV line by line in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to write to a CSV line by line?

  1. How to write to a CSV line by line?

    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')

  2. write to a CSV line by line

    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')

Method 1

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 there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

Method 2

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)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read