1

I want to create 2 csv files.

I have 2 array in one function then i am looping through it and calling another function to write into an csv file so it will create 2 csv files

import time
import datetime
import csv
time_value = time.time()
def csv_write(s):
    print s
    f3 = open("import_"+str(int(time_value))+".csv", 'wt')
    writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
    writer.writerow(s)
    f3.close()

def process_array():
    a = [["a","b"],["s","v"]]
    for s in a:
        csv_write(s)

process_array()

The whole idea is to create 2 csv files since it has 2 array elements but the above code just overwrites the files and the codes creates only one csv file at end

So if the array has 10 elements then the code should create 10 csv files

How to do it?

3 Answers 3

1

First convert it into Dataframe then save it in CSV format

import pandas as pd

a = [["a","b"],["s","v"]]

df=pd.DataFrame(a)

i=len(df)

for j in range(i):
    df.iloc[:,j].to_csv(str(j)+'.csv',index=False)

After executing this code, you will get two csv files (As length of array is two)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to add the argument into the file name:

f3 = open("import_"+"".join(s)+"_"+str(int(time_value))+".csv", 'wt')

In this case you will have two files (with "ab" and "sv" in the names) if a contains two elements from your example. Here we concatenate all the items of s, so it is not the best solution (since it is possible that result of this concatenation is the same for different elements of the list a).

So, I'd recommend to use this solution:

In the for loop you can count number of elements:

idx = 0
for s in a:
    csv_write(s, idx)
    idx = idx + 1

In this case you need to extend your function csv_write (add one more argument):

def csv_write(s, idx):
    print s
    f3 = open("import_"+str(i)+"_"+str(int(time_value))+".csv", 'wt')
    ...

Comments

0

I'm not an experienced Python guy but it looks like the time value that names the files is being defined once outside of code dealing with the numbers of elements. Each array their would have the same time value.csv name as that time value was defined at the start and isn't called again. Try nesting the time value bit in the for loop before the write command.

Comments

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.