Jens Bodal
Jens Bodal

Reputation: 1757

Create and write to files based on list with like items

I have a CSV file with 237 lines of transactions, I've already figured out to group, sort, and create a new CSV file with the transactions in the correct order sorted by account number. However I'd like to go one step further and create multiple CSV files based on the account number with all of that account number's transactions.

I think what I'd like to do just append each line to the appropiate CSV file based on the account number, but I'd like to do this dynamically so I don't have to create each variable since there is always an unknown number of account numbers.

Account #, Date, Dollar Amount (stored as heading)
001, 1/1/11, $25
001, 1/1/11, $20
002, 1/1/11, $15
003, 1/4/11, $19

So with this data I'd like to create three separate CSV files based on the Account number. I am not looking for someone to write the code, but I am hoping there is some module in Python I'm unaware of that involves this type of process. If someone could please point me in the right direction I'd greatly appreciate it.

Thank you

Upvotes: 1

Views: 160

Answers (3)

eyquem
eyquem

Reputation: 27575

No need of CSV interface, I prefer this:

from collections import defaultdict
from os.path import getsize

with open('accounts.csv') as f:

    first_line = f.readline()

    d = defaultdict(list)
    for line in f:
        d[line.split(',')[0]].append(line)

    for account,lines in d.iteritems():
        with open(account+'.csv','a') as f:
            if getsize(account+'.csv')==0:
                f.write(first_line)
            f.write(''.join(lines))

The file is read only one time

Upvotes: 0

Bora Caglayan
Bora Caglayan

Reputation: 151

This is a quick (and probably not so efficient) solution.

from sets import Set
import csv

source = list(csv.reader(open("account_file.csv")))

accounts = Set(line[0] for line in source)

for account in accounts:
    out = open(account+".csv","w")
    out.write( "\n".join(",".join(x) for x in source if x[0] == account))
    out.close()

Upvotes: 1

Michał Niklas
Michał Niklas

Reputation: 54302

I don't think there is such module. I would create separate lists for each account operations and put them on the dictionary where key is account number. Then after iterating whole input file you can save each list to separate .csv file.

If your input file is already sorted then you can simply copy line to output file, then when account changes close output file and open next output file for new account.

Upvotes: 1

Related Questions