Jolijt Tamanaha
Jolijt Tamanaha

Reputation: 333

Making a loop to write new lines to a txt file using python

I'm trying to get the script to read a text file of Congress members in which each line is formatted like this:

Darrell Issa (R-Calif)

I want it to print a line to a different file that's formatted like this (notice the added comma):

Darrell Issa,(R-Calif)

For some reason the script below works but it only does it for the first line. How do I get it to execute the loop for each line?

basicfile = open('membersofcongress.txt', 'r')

for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[+0:partyst-1]
   outfile = open('memberswcomma.txt','w')
   outfile.write(name)
   outfile.write(",")
   outfile.write(party)
   outfile.close()

basicfile.close()
print "All Done"

Thank you in advance for your help.

Upvotes: 1

Views: 14555

Answers (2)

Mohamed Fathi
Mohamed Fathi

Reputation: 14

ok a few things to fix this, use 'a' mode to open your outfile and open it just before the loop, close the outfile after the loop and not inside it. something like this should work (tested it)

basicfile = open('membersofcongress.txt', 'r')
outfile = open('memberswcomma.txt','a')
for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[0:partyst-1]
   outfile.write(name)
   outfile.write(",")
   outfile.write(party)

outfile.close()
basicfile.close()
print "All Done"

Upvotes: 0

Lafexlos
Lafexlos

Reputation: 7735

According to documentation,

'w' for only writing (an existing file with the same name will be erased)

When you open your output file with w, loop keeps creating a new txt file for each line. Using a would be better.

basicfile = open('membersofcongress.txt', 'r')

for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[+0:partyst-1]
   outfile = open('memberswcomma.txt','a')
   outp = name + "," + party + "\n"
   outfile.write(outp)
   outfile.close()

basicfile.close()

EDIT: Much better solution would be,
You open your output file at the begining of the loop instead of inside of it.

basicfile = open('membersofcongress.txt', 'r')
outfile = open('memberswcomma.txt','w')

for line in basicfile:
   partyst = line.find('(')
   partyend = line.find(')')
   party = line[partyst:partyend+1]
   name = line[+0:partyst-1]
   outp = name + "," + party + "\n"
   outfile.write(outp)

outfile.close()
basicfile.close()

Upvotes: 3

Related Questions