使用python循环向txt文件写入新行

2024-05-29 00:18:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让脚本读取国会成员的文本文件,其中每一行的格式如下:

达雷尔·伊萨(R-Calif)

我希望它打印一行到另一个格式如下的文件(注意添加的逗号):

达雷尔·伊萨(R-加州)

出于某种原因,下面的脚本可以工作,但它只对第一行执行。如何让它为每一行执行循环?

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"

提前谢谢你的帮助。


Tags: nametxt脚本closeparty格式lineopen
2条回答

根据documentation

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

当您使用w打开输出文件时,loop会为每一行创建一个新的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()

要解决这个问题,可以使用'a'模式打开输出文件,在循环之前打开它,在循环之后关闭输出文件,而不是在循环之内。 像这样的东西应该有用(测试过了)

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"

相关问题 更多 >

    热门问题