Search code examples
pythontext-fileslimit

How to add number of lines limit to a text file in python


I am currently doing a python project as part of my syllabus. One of the criteria is that there should be a maximum of 20 players. How can I set this limit? I know how to set them to normal variables inside python but not in an external text file. Could this be done by limiting the number of times the user can input a player? I have added comments so that you know what each statement is doing. And where to add in the code if needed.

def playerMenu():
    runningplayer = True
    while runningplayer == True:
        time.sleep(0.3)
        print("\n====================================================")
        print("************|Welcome to The Player Menu|************")
        print("====================================================")
        time.sleep(0.2)
        choice = input('''
====================================================

    A: Add Player & Score
    B: Delete Player
    C: View Scores
    D: Back To Main Menu
    E: Exit Menu

====================================================
\nPlease select what you wish to do: ''')

# This ELIF statement will allow the user to write the name and score of the player.
        if choice == "A" or choice == "a":
            save_name = input('Enter your name: ').title()
            save_score = input('Enter your score: ')
            text_file = open("highscores.txt", "a")
            text_file.write("\n" + save_name + ' | ' + save_score + "\n")
            text_file.close()
            text_file = open("highscores.txt", "r")
            whole_thing = text_file.read()
            print (whole_thing)
            text_file.close()
            
# This ELIF statement will allow the user to delete a player and their score from the text file.
        elif choice == "B" or choice == "b":
            print("These are the current players and their score:")
            text_file = open("highscores.txt", "r")
            whole_thing = text_file.read()
            print(whole_thing)
            text_file.close()
            time.sleep(0.3)
            save_delete = input("Please enter the name of the player you wish to delete: ") + " | "
            #print(f"save_delete = {save_delete}")
            with open("highscores.txt", "r") as f:
                lines = f.readlines()
                #print(lines)
            with open("highscores.txt", "w") as f:
                for line in lines:
                    if not(line.startswith(save_delete)):
                        f.write(line)

# This ELIF statement will allow the user to view the scores of all players.
        elif choice == "C" or choice == "c":
            with open('highscores.txt', encoding = 'utf-8', mode = 'r') as my_file:
                file = open("highscores.txt", encoding='utf-8', mode='r')
                text = file.read()
                print(text)

Solution

  • So, before you add the player, you can read the lines from the file. If the number of lines is 20, do not add the player but if it's less you can add them.

    A simple way to do this is to use readlines() this will return a list with each line. Then you can check the length of the list.

    # This ELIF statement will allow the user to write the name and score of the player.
    save_name = input('Enter your name: ')
    save_score = input('Enter your score: ')
    text_file = open("untitled.txt", "r")
    whole_thing = text_file.readlines()
    text_file.close()
    if len(whole_thing) < 20:
        text_file = open("untitled.txt", "a")
        text_file.write("\n" + save_name + ' | ' + save_score + "\n")
        text_file.close()
    text_file = open("untitled.txt", "r")
    whole_thing = text_file.readlines()
    print (whole_thing)
    text_file.close()