#!/bin/env python #-*- coding: utf-8 -*- import sys import os import csv import codecs import datetime import unicodedata class UTF8Recoder: """ Iterator that reads an encoded stream and reencodes the input to UTF-8 http://docs.python.org/library/csv.html """ def __init__(self, f, encoding): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def next(self): return self.reader.next().encode("utf-8") class UnicodeReader: """ A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. http://docs.python.org/library/csv.html """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): f = UTF8Recoder(f, encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def next(self): row = self.reader.next() return [unicode(s, "utf-8") for s in row] def __iter__(self): return self def CreateOutFile(origFile): (o, fileWithExt) = os.path.split(origFile) (fileNoExt, o) = os.path.splitext(fileWithExt) outfileName = fileNoExt + ".qif" if os.path.exists(outfileName): print "Target (" + outfileName + ") does already exist" sys.exit(1) outfile = codecs.open(outfileName, 'w', 'ascii') #outfile = codecs.open(outfileName, 'w', 'iso-8859-1') outfile.write('!Type:Bank\n') return outfile def ToAscii(text): text = text.replace(u'ä', 'ae') text = text.replace(u'ö', 'oe') text = text.replace(u'ü', 'ue') text = text.replace(u'ß', 'ss') text = text.replace(u'Ä', 'AE') text = text.replace(u'Ö', 'OE') text = text.replace(u'Ü', 'UE') #simply "flatten" the rest... return unicodedata.normalize('NFKD', text).encode('ascii','ignore') def ToUsDate(date): t = datetime.datetime.strptime(date, "%d.%m.%Y") return t.strftime("%m/%d/%Y") def WriteTrasaction(outFile, date, payee, amount): outFile.write('D' + ToUsDate(date) + '\n') outFile.write('P' + ToAscii(payee) + '\n') outFile.write('T' + amount + '\n') #outFile.write('MBemerkung zur Buchung\n') #outFile.write('LKategorie:SubKat\n') outFile.write('^\n') def Import(file): reader = UnicodeReader(codecs.open(file, 'rb'),csv.excel, 'cp1252', delimiter=';') #three lines of garbage reader.next() reader.next() reader.next() #ignore header reader.next() outFile = CreateOutFile(file) for row in reader: #KontoNr;Buchungstag;Text;Betrag;Währung WriteTrasaction(outFile, row[1], row[2], row[3]) outFile.flush() outFile.close() if __name__ == "__main__": if len(sys.argv) != 2: print "usage: " + sys.argv[0] + " " sys.exit(1) file = sys.argv[1] if not os.path.isfile(file): print "Can not access file: " + file sys.exit(1) Import(file)