Reputation: 77
I have been working on a program that reads from a file using Python 3.5.2, where the results are output in the form of a table. The file I have stored the data like a CSV (but as a text file)
I'm not sure why but when I run the procedure, the result seems to have a two space indent after the first record.
def display():
with open("StudentScores.txt","r") as Scores:
print("{0:<10} {1:<10} {2:<5}".format("\nFIRSTNAME","SURNAME","SCORE"))
for eachLine in Scores:
eachLine.strip()
each=eachLine.split(",")
print("{0:<10} {1:<10} {2:<5}".format(each[0],each[1],each[2]),end="",sep="")
The text file I'm using:
Ralph,White,41
Maria,Cox,26
Sharon,Barnes,88
Eric,Garcia,31
Cheryl,Scott,60
Ron,Cooper,11
Lori,Ramirez,34
William,Jones,60
Evelyn,Baker,28
Janice,Sanders,10
Ralph,White,41
Maria,Cox,26
Sharon,Barnes,88
Eric,Garcia,31
Cheryl,Scott,60
Ron,Cooper,11
Lori,Ramirez,34
William,Jones,60
Evelyn,Baker,28
Janice,Sanders,10
And finally the output I've been receiving (copied from IDLE)
FIRSTNAME SURNAME SCORE
Ralph White 41
Maria Cox 26
Sharon Barnes 88
Eric Garcia 31
Cheryl Scott 60
Ron Cooper 11
Lori Ramirez 34
William Jones 60
Evelyn Baker 28
Janice Sanders 10
Ralph White 41
Maria Cox 26
Sharon Barnes 88
Eric Garcia 31
Cheryl Scott 60
Ron Cooper 11
Lori Ramirez 34
William Jones 60
Evelyn Baker 28
Janice Sanders 10
Any suggestions? I've only been using Python for 3 days on a new laptop (Windows 10), if that's any help.
Upvotes: 0
Views: 2648
Reputation: 280446
When you read lines from a file:
for eachLine in Scores:
the lines include the newline character at the end (except maybe the last line, if the file is missing a final newline character).
When you call strip
:
eachLine.strip()
that doesn't mutate eachLine
. It returns a new, stripped string, which you promptly ignore and discard. eachLine
still has a trailing newline.
When you call split
:
each=eachLine.split(",")
each[2]
has that trailing newline.
When you print each[2]
with replacement field {2:<5}
, each[2]
contains 2 digits and a newline. <5
left-aligns it in a field of width 5, padding the end with spaces, so it prints two digits, a newline, and two spaces on the next line.
To fix this, actually store the return value of strip
, stop space-padding the score field, and stop passing end=""
. sep=""
is also redundant, since you're only print
ing one string at a time:
def display():
with open("StudentScores.txt","r") as Scores:
print("{0:<10} {1:<10} {2}".format("FIRSTNAME","SURNAME","SCORE"))
for eachLine in Scores:
eachLine = eachLine.strip()
each = eachLine.split(",")
print("{0:<10} {1:<10} {2}".format(each[0],each[1],each[2]))
Upvotes: 2
Reputation: 1437
Change this line:
print("{0:<10} {1:<10} {2:<5}".format(each[0],each[1],each[2]),end="",sep="")
To this:
# Just changing <5 to <3
print("{0:<10} {1:<10} {2:<3}".format(each[0],each[1],each[2]),end="",sep="")
And it should print with the formatting you want.
Upvotes: 0