Lemon8ter
Lemon8ter

Reputation: 55

How to add/write a heading to an .txt file

I am trying to add a heading to my newly created .txt file with an outfile command. However, my intended heading ("Teams Wins Losses") doesn't appear on the first line, rather, it is preceding each line of data.

Code:

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() 

Output:

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

Upvotes: 0

Views: 93

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114330

This answer is an appendix to @QueenSvetlana's. In addition to using a with block, you could also consider using print instead of f.write. The interface is cleaner (separators and newlines are inserted automatically). It also removes the need to create formatted strings in-memory to avoid multiple calls to 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)

This approach is less flexible than using direct writes, but turns out to be more concise in this case.

Upvotes: 0

user9386524
user9386524

Reputation:

This code:

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() 

Should be written like this:

Use the with keyword, it ensures that the resources are cleaned up at the end.

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")

Note: As pointed out in the comments using + to concat strings can have negative side effects. Many pages on SO explain this topic, instead use .format() to display your strings

Upvotes: 1

Related Questions