user8620863
user8620863

Reputation:

Why does my code make a new line

I'm tasked with taking some baseball team statistics from one txt file, finding the percent of games won, and outputting that to a separate file.

My code is as follows

infile = open("ALE.txt", "r")
outfile = open("ALE_sorted.txt", "w")

for line in infile:
    data = line.split(',')
    wins = eval(data[2])
    percentage = 162 / wins

    outfile.write(str(data[0]) + ", " + data[1] + ", " + data[2] + ", " + 
str(round(percentage, 3)) + "\n")

infile.close()
outfile.close()

The initial txt file looks like this in the format (teams, wins, losses):

Baltimore,93,69
Boston,69,93
New York,95,67
Tampa Bay,90,72
Toronto,73,89

And while my code correctly calculates the percentage of games won, it creates a line and I can't figure out why, looking exactly like this:

Baltimore, 93, 69
, 2.348
Boston, 69, 93
, 1.742
New York, 95, 67
, 2.418
Tampa Bay, 90, 72
, 2.25
Toronto, 73, 89, 1.82

It should only be 5 lines, not creating a new line right before the third comma every time. I've tried removing the "\n" but to no avail. Any tips?

Upvotes: 0

Views: 68

Answers (3)

Noel Llevares
Noel Llevares

Reputation: 16037

Your data[2] includes a newline. Just strip it away.

Upvotes: 0

Amadan
Amadan

Reputation: 198314

"line" is defined as "string of characters ending in line terminator". Thus, after you read the first line, line contains "Baltimore,93,69\n". After split, data is ["Baltimore", "93", "69\n"]. When you print out data[2], there's a newline - because you never removed it.

Use data = line.rstrip('\n').split(',') to remove it. rstrip removes specified characters from the end of the string. .rstrip() would also work, but it removes any whitespace (such as trailing spaces).

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

Try changing:

data = line.split(',')

to:

data = line.strip().split(',')

Upvotes: 3

Related Questions