首页 > 解决方案 > VSCode 当我从 python 的文本文件中读取信息时,它还删除了文本文件中的所有内容

问题描述

这是我用来从文件中读取的代码

def load_leaderboard(file_name, leader_names, leader_scores):

  leaderboard_file = open(file_name, "r")  # need to create the file ahead of time in same folder

  # use a for loop to iterate through the content of the file, one line at a time
  # note that each line in the file has the format "leader_name,leader_score" for example "Pat,50"
  for line in leaderboard_file:
    leader_name = ""
    leader_score = ""    
    index = 0

    # TODO 1: use a while loop to read the leader name from the line (format is "leader_name,leader_score")
    while (line[index] != ","):
        leader_name = leader_name + line[index] 
        index = index + 1
    print("leader name is " + leader_name)  


    # TODO 2: add the leader name to the list
    leader_names.append(leader_name)

    
    # TODO 3: read the player score using a similar loop'
    index += 1
    while(line[index] != '\n'):
        leader_score += line[index]
        index += 1
    print('The score for this person is:' + leader_score)

    
    # TODO 4: add the player score to the list


  leaderboard_file.close()

当此代码运行时,它可以正常工作,只有从文本文件中读取所有内容后,它才会从文本文件本身中删除所有信息。我认为这会很好,因为我将 open() 函数置于只读状态。但它不是,我如何防止它从原始文件中删除信息?

标签: pythonpython-3.xfile

解决方案


推荐阅读