Adding A New Column On CSV With Python
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
Solution 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")
Solution 2:
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!
Solution 3:
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)
Post a Comment for "Adding A New Column On CSV With Python"