Как прочитать текстовый файл и преобразовать числа в целые числа, чтобы получить общее значение - PullRequest
0 голосов
/ 23 октября 2019

Я пытаюсь прочитать GolferScores из txt-файла, который был создан и считан с накопления итогового значения, а затем определить среднее значение. Я хочу. Я пытался собрать все это в своей функции GolfRead

Я пытался создавать объекты while и readline (), но мне чего-то не хватает.

def Main():
    import time  #Imports time module
    time.sleep(2)#delay of 2 seconds

    Welcome() #Call Welcome Function

    #Constants for the menu choices


    AverageGolfScore = 0 #Initialize Variable

    #Display the menu
    GolfMenu()

def Welcome():
    print('This is a menu-driven program\n' +
          'that allows you to write, append and read\n' +
          'data to and from a file.\nProgram developed by Robert 
           Hernandez')
    print('')#Prints blank space

#Append Choice Menu Function
def GolfAppend():
    #Warn User
    confirm = input('This will add data to an existing data file.\nIf you 
                    do not wish to continue' +' with this action\n' + 'hit N or n to return to 
                    menu.\n' +
                    'Otherwise press Enter key to continue: ')

#While Validation Loop
while confirm != 'N' and confirm != 'n' and confirm != '':
    print('Invalid Input')
    confirm = input('Press N or n to return to menu.\nOtherwise press Enter key to continue: ')

#Warn User if statement
if confirm == 'N' or confirm == 'n':
    GolfMenu()     
elif confirm == '':

    #Get the number of golfers records to create.
    NumGolfers = int(input('How many golfers records ' +
                           'do you want to create? '))

    #Validate # of golfers input
    NumGolfers = ValidNumGolfers(NumGolfers)

    #Open a file for writing.
    GolfFile = open('golfers.txt', 'a')



    #Get each golfers data and write it to
    #to the file
    for count in range(1, NumGolfers + 1):

        #Get the data for a golfer
        print('Enter the data for golfer #' , count, sep='')
        GolferName = input('Name: ')
        ValidName(GolferName)
        GolferScore = int(input('Score: '))
        ValidScore(GolferScore)

        #Write data to a file.
        GolfFile.write(GolferName.capitalize() + '\n')
        GolfFile.write(str(GolferScore) + '\n')

        #Display a blank line.
        print()

    #Close the file
    GolfFile.close()
    print('Golfers records written to Golfers.txt. ')

    #Returns to menu
    GolfMenu()

#Read Choice Menu Function
def GolfRead():
    try:
        TotalScore = 0

        #opens file in read only mode
        GolfFile = open("golfers.txt","r")

        #Read the first line from the file
        #which is the name field of first
        #record
        GolferName = GolfFile.readline()

        #If a field was read continue processing.
        while GolferName != '':

            GolferScore = int(GolferScore)
            TotalScore += GolferScore

            #Read golf score
            GolferScore = GolfFile.readline()


            #Strip the newlines from the fields
            GolferName = GolferName.rstrip('\n')
            GolferScore = GolferScore.rstrip('\n')

            #Display the record.
            print('Name:',GolferName)
            print('Score:',GolferScore)
            print(TotalScore)
            print('')

            #
            GolferName = GolfFile.readline()

        #Close the file
        GolfFile.close

        #Return to menu
        GolfMenu()

    except:
        print('ERROR: File not found')
        print('')

        #Returns to menu
        GolfMenu()

#Menu Choice Function
def GolfMenu():
    print(' Menu')
    print('1) Record golf data to file')
    print('2) Read golf data from file')
    print('3) Quit Program')
    print('')

    #The choice variable controls the loop
    #and hold the user's menu choice
    Choice = 0

    #Get the user's choice
    Choice = int(input('Enter your choice: '))
    print('')

    #Perform the selected action
    if Choice == 1:
         GolfAppend()
    elif Choice == 2:
        GolfRead()
    elif Choice == 3:
        print('Exiting the program...')
    else:
        print('Error: Invalid selection.')
        GolfMenu()

   def ValidName(GolferName):
        while GolferName == "":
            GolferName = input('No data inputted.\nName: ')
            GolfFile.write(GolferName.capitalize() + '\n')

   def ValidScore(GolferScore):
        while GolferScore < 58 or GolferScore > 180:
            GolferScore = int(input('Not a valid score:\nPlease input' +
                                'a score between 58 and 180\nScore: '))
            GolfFile.write(str(GolferScore) + '\n')

   def ValidNumGolfers(NumGolfers):
        while NumGolfers < 1 or NumGolfers > 20:
            NumGolfers = int(input('Invalid Input:\nPlease input a number 
                                 between 1 and 20\n' +
                                'How many golfers records ' +
                                'do you want to create? '))
        return NumGolfers



#Call the main function
Main()

Чтобы иметь возможность читать содержимоефайла и затем он также показывает среднюю оценку игрока в гольф со всем содержимым файла.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...