0

I have a csv file like this:

A,Film, Yes 
B,Grass,No
C,Bottle,No  
D,Love,Yes
E,Red,No

And I have a list from the system is like this:

['No','No','Yes','Yes','No'] 

How can i add the list to the new column and my expectation is like this:

    A,Film, Yes,No
    B,Grass,No,No
    C,Bottle,No,Yes
    D,Love,Yes,Yes
    E,Red,No,No

How can i do that?

JFroz
  • 11
  • 3

4 Answers4

0

Using the CSV module.

Demo:

import csv
toAdd = ['No','No','Yes','Yes','No']
with open(filename, "r") as infile:
    data = [i.strip().split(",") for i in infile.readlines()]

with open(filename, "w") as outfile:
    writer = csv.writer(outfile, delimiter=",")
    for i, value in enumerate(toAdd, 0):
        v = data[i]
        v.extend([toAdd[i]])
        writer.writerow(v)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can use zip:

import csv
with open('filename.csv') as f:
  with open('filename.csv', 'w') as f1:
    headers = ['No','No','Yes','Yes','No'] 
    data = list(csv.reader(f))   
    write = csv.writer(f1)
    write.writerows([a+[b] for a, b in zip(data, headers)])
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

For more complex operations, the csv module should be considered. But to only add the content of a simple list as the last column of a file, simple string processing should be enough:

lastcol = ['No','No','Yes','Yes','No']
with open(infile) as fdin, open(outfile, "w") as fdout:
    for i, line in enumerate(fdin):
        print(line.rstrip(), lastcol[i], sep=",", file=fdout)

Above just assumes that list is at least as long as the file...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-1

If you want to use the pandas library, you can do:

import pandas as pd

list = ['No','No','Yes','Yes','No'] 
df = pd.read_csv('data.csv')
df['new_column'] = list
df.to_csv('modified_data.csv')
amit kumar
  • 20,438
  • 23
  • 90
  • 126
riccardo nizzolo
  • 601
  • 1
  • 7
  • 21