[Tutor] Suggestions to improve this first effort?

C B Gambrell gulfgeek at gmail.com
Sat Feb 16 21:49:12 CET 2008


I am just getting started with Python and wonder if folks here might
look at this attempt in Python and offer me your thoughts.

Several years ago I used QBasic to convert one our reports to a csv
file so we could import the data into another program.  That very old
QBasic script has been serving me well but I decided to try to make it
work in Python.  I used the same logic in Python I had used in QBasic
and the resulting output is exactly what I need.

Here is how the data looks in the input file.

=====
=====
.block
  name 1
  address1
  city st
  11111
.endblock
.report


.block
  name 2
  address 2
  city st
  11111
.endblock
.report
====
====

The input file goes on for several thousand addresses.

Here is what worked for me in QBasic.

===
===
clin1$ = ""
clin2$ = ""
infile$ = "ad.txt"
outfile$ = "ad.csv"
'
OPEN infile$ FOR INPUT AS #1
OPEN outfile$ FOR OUTPUT AS #2
'
DO WHILE NOT EOF(1)
        LINE INPUT #1, lin$
        clin1$ = RTRIM$(LTRIM$(lin$))
        IF clin1$ = "" THEN
                clin1$ = ""
        ELSEIF clin1$ = ".report" THEN
                clin1$ = ""
        ELSEIF clin1$ = ".block" THEN
                clin1$ = ""
        ELSEIF clin1$ = ".endblock" THEN
                WRITE #2, MID$(clin2$, 4)
                PRINT MID$(clin2$, 4)
                clin2$ = ""
        ELSE
                clin2$ = clin2$ + CHR$(34) + CHR$(44) + CHR$(34) + clin1$
        END IF
LOOP
END
====
====

And here is my I got work for me in Python.

===
===
import sys
infile=sys.argv[1]
outfile=sys.argv[1]+".csv"

f1=open(infile)
f2=open(outfile, 'w')

s2=""

for line in f1:
	s=line.strip()
	if s=="":
		continue
	elif s==".block":
		continue
	elif s==".report":
		continue
	elif s==".endblock":
		s="\n"
		s2=s2[:-1]+s
		f2.write(s2)
		s2=""
		continue
	s2=s2+"\""+s+"\""+","	

f1.close()
f2.close()
===
===

The script works but what you suggest to improve the logic or make the
script more Pythonic?

Thanks for this list.  I am enjoying reading and learning from the
many conversations here.

Charles


More information about the Tutor mailing list