0

I've made a leader board for a larger quiz that I've been working on. I've wrote code that opens the text file and does "\n" to print the things in that text file on different lines when ran. However, when run, it doesn't just display the name and their score like it should, it also displays the newline \n that should be hidden. How do I fix this? This code is where I'm having issues:

    if score == 3:
        print("You have reached the maximum amount of points and have reached the top of the current leaderboard, congrats.")

        leaderboard = open ("leaderboard.txt","r")

        write_in_file(leaderboard, score, username)

        topscores = leaderboard.readlines()

        print(topscores)

any help would greatly be appreciated as this assessment has a time limit that is quickly approaching.

Pibben
  • 1,876
  • 14
  • 28
seshydave
  • 1
  • 1
  • 1
    Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – GPhilo Oct 16 '19 at 09:34
  • We can't really help without knowing the formatting in your `leaderboard.txt` file. Moreover, it seems very curious to me that you first open the leaderboard in read mode and then use a function you made which seems to be writing in the file. I think it would be best if you share also `write_in_file()`. – Mathieu Oct 16 '19 at 09:34
  • 1
    `[x.strip() for x in leaderboard.readlines()]` – MohitC Oct 16 '19 at 09:35

2 Answers2

0

You could specify that the end is a newline in the print() statement itself with

print(topscores, end="\n")
Reza Rahemtola
  • 1,182
  • 7
  • 16
  • 30
RishiC
  • 768
  • 1
  • 10
  • 34
0

As MohitC suggested, you can use list comprehension. In the code you posted, you open the file, but you don't close it. I suggest you close it, or even better, use this syntax in the future:

with open("myfile", "mode") as file:
    # operations to do.

The file is automatically closed when you're out of the scope.

So, using these 2 suggestions, here's a code that you could use:

if score == 3:
    print("You have reached the maximum amount of points and have reached the top of the current leaderboard, congrats.")

    with open("leaderbord.txt", "w+") as leaderbord:
        write_in_file(leaderboard, score, username)
        topscores = leaderboard.readlines()

    # we're out of the with open(... scope, the file is automatically closed
    topscores = [i.strip() for i in topscores] # @MohitC 's suggestion
    print(topscores)
ImranD
  • 320
  • 1
  • 6