1

I have the following list of numbers: ['Number', 1,2,3,4]

If I have the following CSV file:

`Name`    
`First`
`Second`
`Third`
`Fourth`

How do I add my list of numbers to it and make it look like this:

`Name    Number`
`First   1`
`Second  2`
`Third   3`
`Fourth  4`

3 Answers 3

1

You can use fileinput.input with inplace=True to modify the original file:

import fileinput
import sys
l =['Number', 1,2,3,4]
for ind, line in enumerate(fileinput.input("in.csv",inplace=True)):
    sys.stdout.write("{} {}\n".format(line.rstrip(), l[ind]))

Input:

Name    
First
Second
Third
Fourth

Output:

Name Number
First 1
Second 2
Third 3
Fourth 4

Or write to a tempfile and move with shutil.move to replace the original file:

l =['Number', 1,2,3,4]
from shutil import move
from tempfile import NamedTemporaryFile
with open('in.csv') as csvfile, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    r = csv.reader(csvfile)
    wr = csv.writer(temp,delimiter=" ")
    for row,new in zip(r,l):
        wr.writerow(row+[new])

move(temp.name,"in.csv")
Sign up to request clarification or add additional context in comments.

3 Comments

I really like this method. Can you comma separate the rows on the csv file? I am having trouble figuring out how to do it on your code.
with the second use delimiter=",", with the first use sys.stdout.write("{},{}\n".format(line.rstrip(), l[ind]))
No worries, glad it helped.
0

Not an elegant way but It works:

#!/usr/bin/python

import csv
import sys

def csv_to_dict(csv_file_path):
    csv_file = open(csv_file_path, 'rb')
    csv_file.seek(0)
    sniffdialect = csv.Sniffer().sniff(csv_file.read(10000), delimiters='\t,;')
    csv_file.seek(0)
    dict_reader = csv.DictReader(csv_file, dialect=sniffdialect)
    csv_file.seek(0)
    dict_data = []
    for record in dict_reader:
        dict_data.append(record)
    csv_file.close()

    return dict_data

def dict_to_csv(csv_file_path, dict_data):
    csv_file = open(csv_file_path, 'wb')
    writer = csv.writer(csv_file, dialect='excel')

    headers = dict_data[0].keys()
    writer.writerow(headers)

    for dat in dict_data:
        line = []
        for field in headers:
            line.append(dat[field])
        writer.writerow(line)

    csv_file.close()

if __name__ == '__main__':
    org_path = sys.argv[1]
    new_path = sys.argv[2]
    your_array = ['Number', 1, 2, 3, 4]

    org_csv = csv_to_dict(org_path)
    new_data = []
    for line in org_csv:
        new_line = dict()
        new_line['Name'] = line['Name']
        new_line[your_array[0]] = your_array[org_csv.index(line)+1]
        new_data.append(new_line)
    if new_data:
        dict_to_csv(new_path, new_data)

Hope that will help!

Comments

0
import csv

with open('existing_file.csv', 'rb') as infile:
    reader = csv.reader(infile)
    your_list = list(reader)

list2 = ['Number', 1,2,3,4]

zipped= zip(your_list, list2)

with open("test.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    writer.writerows(zipped)

1 Comment

don't you think so if file is huge then every thing will be rewrite and its overload to the system ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.