Python print formatting carries to next line

Viewed 33

very new to Python and having a weird issue which I can't find a solution for online.

I need to take a binary file containing data and display it in a table format, which is almost working except that it pushes the end of the first line to the next and throwing everything off as shown below.

Table print issue

Code for the function to view the binary file data as below. As its for an assignment I don't think I can use 3rd party table modules like tabulate so this was my attempt at just doing it with string formatting. It was moving the end of the each line to the next when printing with an entire empty line so I added the end=' ' bit to the print statement but still no dice. There's probably an easier way of displaying the data as a table anyway but I'd be happy with it if I could just figure out why it won't stay on one line when printing the data under the headers :|

def functionRetrieve():
    while True:
        filename = input("Please enter a binary file name:")
        try:
            open(filename + ".bin", 'r')
        except FileNotFoundError:
            print("Wrong file name or file type")
        else:
            break
    filename = filename + ".bin"
    print("\033[4m|{:^24}|{:^24}|{:^14}|{:^14}|{:^14}|{:^14}|\033[0m".format("Last Name", "First Name", "Games Played", "Total Points", "Average", "Position"))
    with open(filename, 'rb') as textfile:
        for line in textfile:
            line = line.decode('utf-8')
            data = list(line.split(","))
            lastname = data[0]
            firstname = data[1]
            gamesplayed = data[2]
            totalpoints = data[3]
            average = data[4]
            position = data[5]
            print("|{:^24}|{:^24}|{:^14}|{:^14}|{:^14}|{:^14}|".format(lastname, firstname, gamesplayed, totalpoints, average, position), end='')
      
1 Answers

with end='' you're overwriting the default end value of print from newline '\n' to ''. So basically you're printing one loooong line instaed of multiple lines. Thats why each new print seems to be with one additional space indent. The lines are appending instead of printing below eachother.

In your header row you do not do this, that is why the first row looks "normal". This should fix it:

print("|{:^24}|{:^24}|{:^14}|{:^14}|{:^14}|{:^14}|".format(lastname, firstname, gamesplayed, totalpoints, average, position))
Related