如何在.txt文件中添加/写入标题

时间:2018-02-22 02:47:29

标签: python

我正在尝试使用outfile命令为新创建的.txt文件添加标题。但是,我的预定标题("团队赢得损失")并没有出现在第一行,而是出现在每行数据之前。

代码:

def newfile(teams):
     outfile = open("OrderedALE.txt", 'w')
     for team in teams:
        outfile.write("Teams Wins Losses")
        outfile.write(team[0] + ',' + str(team[1]) + ',' +
                      str(team[2]) + ',' + str(round(team[1]/162, 3)) + "\n")

outfile.close() 

输出:

Teams Wins LossesBaltimore,96,66,0.593
Teams Wins LossesNew York,84,78,0.519
Teams Wins LossesToronto,83,79,0.512
Teams Wins LossesTampa Bay,77,85,0.475
Teams Wins LossesBoston,71,91,0.438

2 个答案:

答案 0 :(得分:1)

此代码:

def newfile(teams):
 outfile = open("OrderedALE.txt", 'w')
 outfile.write("Teams Wins Losses")
  for team in teams:
    outfile.write(team[0] + ',' + str(team[1]) + ',' +
    str(team[2]) + ',' + str(round(team[1]/162, 3)) + "\n")

outfile.close() 

应该这样写:

使用with关键字,确保最后清理资源。

with open(filename, 'w') as f:
    f.write("Teams Wins Losses")
    # add a new line after the heading
    f.write("\n")
     for team in teams:
         f.write("{0},{1},{2},{3}".format(team[0]),team[1],team[2],round(team[1]/162, 3))
         # add a new line after each output
         f.write("\n")

注意: 正如在评论中指出的那样使用+连接字符串可能会产生负面影响。 SO上的许多页面都解释了这个主题,而是使用.format()来显示您的strings

答案 1 :(得分:0)

这个答案是@QueenSvetlana's的附录。除了使用with块之外,您还可以考虑使用print代替f.write。界面更清晰(自动插入分隔符和换行符)。它还消除了在内存中创建格式化字符串的需要,以避免多次调用write

with open(filename, 'w') as f:
    print("Teams Wins Losses", file=f)
    for team in teams:
        print(*team, round(team[1] / 162, 3), sep=',', file=f)

这种方法不如使用直接写入方式灵活,但在这种情况下结果更简洁。