Skip to content

Python write line by line to csv

  • by

You can use the Python CSV module or Pandas Data Analysis library to write line-by-line into CSV files.

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

Python writes line by line to CSV

Simple example code Write Data to a CSV File with traditional File Handling in Python. Just open a CSV file in write mode and write our data into the file line by line.

data = [["var112"],
        ["var234"],
        ["var356"]]
with open('csvfile.csv', 'w') as file:
    for line in data:
        for cell in line:
            file.write(cell)
        file.write("\n")

Output:

Python write line by line to csv

Write Data to a CSV File With the csv.writer() Function

import csv
data = [["var1", "val1", "val2"],
        ["var2", "val3", "val4"],
        ["var3", "val5", "val6"]]
with open("csvfile2.csv", "w") as file:
        writer = csv.writer(file)
        writer.writerows(data)

Using Pandas to write and modify the CSV file

import pandas as pd

# create a DataFrame - using the data and headers
hr_df = pd.DataFrame(data, columns  = header_row)

# export the data to a csv file on your computer
hr_df.to_csv('hr.csv')

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading