Select to view content in your preferred language

export a each row from a CSV, with 100s of rows, as an individual text file

3935
3
08-25-2014 01:20 PM
by Anonymous User
Not applicable

Is there a way to have python export a single row from a CSV, with 100s of rows, as an individual text file? IE if you had a CSV with 100 rows you would get 100 .txt files for each row/record.

Thanks in advanced!

0 Kudos
3 Replies
DarrenWiens2
MVP Honored Contributor

The short answer is: yes. Use the CSV module: read a line from the CSV and write the line to a text file.

0 Kudos
JamesCrandall
MVP Frequent Contributor

Alternative option is to use the Pandas library to read in the .csv, go thru the unique rows and export each one to it's own .csv file.  In this example it just names each of the unique .csv files using the first column specified ('fc')

import pandas as pd
import numpy as np


import pandas as pd





def exportCSVbyRow(csvfile):
    src = csvfile
    tab = pd.io.parsers.read_table(str(src), sep=',')
    uniquerows = np.unique(tab['fc'])
    for key in uniquerows:
        print key
        exprow = tab[tab['fc'] == key]
        exprow.to_csv(r'H:\Documents\\' + str(key) + '.csv')





exportCSVbyRow(r'H:\Documents\arlist.csv')


0 Kudos
by Anonymous User
Not applicable

Thanks all for the help, really appreciate it! I was asking for a colleague and it looks like she figured it out. Ill post her script when she sends it. Great community we got here!

M

0 Kudos