an1que
an1que

Reputation: 423

How to write data into separate cells in CSV via Python

I am trying to add a few new columns with fixed values to the csv using python but the all the values are squeezed into one cell instead of separate cells. How to fix this?

My python code:

default_text = 'AoE'

with open('C:/Users/username/Desktop/Output/AoE_test.csv', 'r', newline='') as read_obj, \
        open('C:/Users/username/Desktop/Output/output_1.csv', 'w', newline='') as write_obj:
    csv_reader = reader(read_obj, delimiter=',')
    csv_writer = writer(write_obj, delimiter=',')
    for row in csv_reader:
        row.append(default_text)
        csv_writer.writerow(row)

This is the orginal CSV (AoE_test.csv) which the code reads data from: enter image description here

This is the final output of the csv (output_1.csv) written with the data: enter image description here

I've also tried to comment out the row.append():

    for row in csv_reader:
        # row.append(default_text)
        csv_writer.writerow((row, default_text))

and the output:

enter image description here

I want the addtional column to be written in a separate column in CSV file. Thanks so much in advance!

Upvotes: 0

Views: 729

Answers (1)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

Use pandas when dealing with tables. What you want to do is exactly this:

# pip install pandas
import pandas as pd

default_text = 'AoE'

in_fpath = 'C:/Users/username/Desktop/Output/AoE_test.csv'
out_fpath = 'C:/Users/username/Desktop/Output/output_1.csv', 'w'
df = pd.read_csv(in_fpath, sep=",") # while sep="," is default
df['my_new_col'] = default_text # this works, because 
# pandas takes this one string and repeats it in column
# actually you should put [default_text] * df.shape[0]
# think columns as vertical lists!
df.to_csv(out_fpath)

Upvotes: 1

Related Questions