Dani
Dani

Reputation: 41

Transferring csv files data to one file

I have 10 lists of data in different csv file. each file has one column of information . I want to open each csv file one by one and write it to a file called "file.csv". in a way that data from second file should be saved under the data from the first file.

example:

list1=[['a'], ['b'], ['c'], ['d']] 
list2=[['e'], ['f'], ['g']] 

file.csv= 
a
b
c
d
e
f
g

I have following code, I give the index to the csv_list[1] and it can transfer the data to a file.csv. but when I change the index to csv_list[2] to append the result of new list to the file it deletes previous information and adds information form new list.

How can I add them to the same file with following code.

import csv
import os

csv_list= os.listdir("folder1")
pathname = os.path.join("folder1", csv_list[1])

with open(pathname, encoding='utf8') as f:
    reader = csv.reader(f)
    data = list(reader)    
print (data) 

.

with open("file.csv","w") as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(data)

Upvotes: 0

Views: 47

Answers (1)

Spherical Cowboy
Spherical Cowboy

Reputation: 566

You could do something along the lines of:

if os.path.isfile("file.csv"):
    write_or_append = "a"  # append if csv file already exists
else:
    write_or_append = "w"  # write otherwise
with open("file.csv", write_or_append) as resultFile:
    wr = csv.writer(resultFile, dialect="excel")
    wr.writerows(data)

Upvotes: 1

Related Questions