problem writing to a file each record read

E

Eduardo Biano

I am a python newbie and I have a problem with writing
each record read to a file. The expected output is 10
rows of records, but the actual output of the code
below is only one row with a very long record (10
records are lump into one record). Thank you in
advance for your help. Here is the code:

****************************************

infile = open('c:/grad3650txt.csv', 'r')
outfile = open('c:/idmast01.txt', 'w')

a = 1
b = 10
for line in infile.readlines():
if a <= b:
c1 = line.find(',',0)
ln = line[1:c1]
l2 = line.find('"', c1)
l2a = l2 - 1
l2c = l2
if line[l2a] == '.':
l2b = l2 - 3
if line[l2b] == ' ':
mi = line[l2b+1:l2a+1]
l2c = l2b
else:
mi = ' '
l2c = l2
fn = line[c1+2:l2c]
c2 = line.find(',', l2)
c3 = line.find(',', c2+1)
deg = line[c2+1:c3]
l5 = len(line)
c4 = line.find(',', c3+1)
l7 = c3 + 14
if l5 <= l7 or c4 <= l5:
l8 = l5
if c4 <= l5:
dat = line[c3+1:c4]

#-----------------------------------
# This is the problem code. Ten records
# is lump into 1 row and written
# in the output file.
#
# My expected output is 10 rows.
#-----------------------------------
info = string.join([fn, mi, ln, deg, dat]

outfile.write(info)
#----------------------------------
#
a = 1 + a
else:
a = 1 + a

infile.close()
outfile.close()
# ------------------------------------------------

Thank you very much for your help.





__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
 
P

Peter Otten

Eduardo said:
#-----------------------------------
#  This is the problem code. Ten records
#  is  lump into 1 row and written
#  in the output file.
#
#  My expected output is 10 rows.
#-----------------------------------
info = string.join([fn, mi, ln, deg, dat]

Should probably be ",".join([fn, mi, ln, deg, dat])
outfile.write(info)

You have to add a newline explicitly if you want one:

outfile.write("\n")

Using the csv module that comes with Python may simplify your task a lot.

Peter
 
B

bruno at modulix

Eduardo said:
I am a python newbie and I have a problem with writing
each record read to a file. The expected output is 10
rows of records, but the actual output of the code
below is only one row with a very long record (10
records are lump into one record). Thank you in
advance for your help. Here is the code:

****************************************

infile = open('c:/grad3650txt.csv', 'r')

Use the csv module. It's in the standard lib. And it'll save you lot of
wasted time and aspirin.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top