python - 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() 函数置于只读状态。但它不是,我如何防止它从原始文件中删除信息?
解决方案
推荐阅读
- javascript - javascript 类中的画布
- matlab - 如何使用 MATLAB for 循环创建文件名并读取它们
- android - Flutter中滑动TabBarView()时如何改变Tabs()的形状?
- java - maven-dependency-plugin 和项目内依赖项
- networking - 根据其他变量创建权重变量以形成边
- r - 如何编写一个函数来计算r中数据框中某些列的平均值?
- django - 如何将“绘制标记”控件添加到传单地图和捕获事件?
- php - 检查文件是否在 10 分钟内更新(CRON)
- sql - 更新和比较薪水的存储过程
- aws-cdk - AWS CDK Bootstrap 未将文件发布到 s3