我试图让脚本读取国会成员的文本文件,其中每行的格式如下:
Darrell Issa(加利福尼亚州)
我希望它将一行打印到另一个格式为这样的文件(注意添加的逗号):
Darrell Issa,(加利福尼亚州)
出于某种原因,下面的脚本可以工作,但它只针对第一行。如何让它为每一行执行循环?
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"
提前感谢您的帮助。
答案 0 :(得分:2)
'w'仅用于写入(具有相同名称的现有文件) 擦除)
当您使用w
打开输出文件时,循环会不断为每行创建一个新的txt文件。使用a
会更好。
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()
修改强> 更好的解决方案是, 您可以在循环开始时而不是在循环内部打开输出文件。
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()
答案 1 :(得分:0)
确定一些事情要解决这个问题,使用'a'模式打开你的outfile并在之前循环打开它,关闭outfile 之后< / strong>循环和不在里面它。 这样的事情应该有效(测试它)
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"