[Tutor] Modifying a QIF

spir denis.spir at free.fr
Mon Dec 29 23:52:24 CET 2008


On Mon, 29 Dec 2008 13:18:55 -0700
"Eduardo Vieira" <eduardo.susan at gmail.com> wrote:

> Hello, this weekend I had fun using Python for text processing. I
> needed to change a qif converted from a ofx, using the tool MT2OFX
> (http://www.xs4all.nl/~csmale/mt2ofx/en/index.htm)
> I wanted to change transactions like these:
> D11/14/2008
> MCHEQUE 102 17590807;Cheque or Preauth. Debit
> T-500.00
> N102
> ^
> 
> Into this:
> D11/14/2008
> MCHEQUE 102 17590807;Cheque or Preauth. Debit
> T-500.00
> N102
> PLorne Koehn
> LHousing:Rent
> 
> == That is, insert those given Payee and Category if the transaction
> was a cheque of 500.00
> 
> I came up with these two versions and would like to know which should
> be more efficient or practical. Could you point improvements?
> VERSION ONE:
> f = open('cibc.QIF', 'r').readlines()
> for line in range(len(f)):
>     if f[line] == 'T-500.00\n':
>         f[line+1] += 'PLorne Koehn\nLHousing:Rent\n'
> 
> new = open('cibc.QIF', 'w')
> new.writelines(f)
> 

I would change 'line' --> 'line_nr' or 'lineno'
or
for line,index in enumerate(f)
no!
for index,line in enumerate(f)
;-)

> VERSION TWO:
> f = open('cibc.QIF', 'rw')
> g = open('newresult.qif', 'w')
> flag = 0
> for line in f:
>     if line == 'T-500.00\n':
>         flag = 1
>     elif line.startswith('N') and flag:
>         flag = 0
>         line += 'PLorne Koehn\nLHousing:Rent\n'
> 
>     g.write(line)
> 
> f.close()
> 
> #======
> 
>     One thing like about version 1 is that I can overwrite the same
> file, and don't need to create another one. I haven't figured out how
> to do the same with the second version and overcoming the IOError.

maybe by first writing on a string instead directly to a file -- then flush the
whole text to the same file:

text = ""	# replaces g
...
text += line
...
f = open('cibc.QIF', 'w')
f.write(text)

> Thanks for your attention
> 
> Edu
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


------
la vida e estranya


More information about the Tutor mailing list