如何用Python读写文本文件中的多个值?实现高分榜文件读写功能
嘿,我来帮你搞定这个Python版本的高分榜功能,顺便给你捋清楚Python里读写文本文件多值的基本操作~
一、Python读写文本文件中的多个值
不管是存数值、字符串还是键值对,Python处理起来都比C++更简洁,核心是用open()函数配合上下文管理器with(自动帮你关文件,避免资源泄漏)。
读取多个值
根据文件里的内容格式,有两种常用方式:
- 情况1:纯数值(空格/换行分隔)
比如文件data.txt内容是:
100 200 300 400 500
可以一次性读取并转成整数列表:
with open("data.txt", "r") as f: # 读取所有内容,按空白字符拆分后转成整数 values = list(map(int, f.read().split())) print(values) # 输出: [100, 200, 300, 400, 500]
也可以逐行处理,适合大文件:
values = [] with open("data.txt", "r") as f: for line in f: line_values = list(map(int, line.strip().split())) values.extend(line_values)
- 情况2:带关联信息(比如名字+分数,每行一组)
比如文件scores.txt内容是:
Alice 95 Bob 88 Charlie 92
可以读取成包含元组的列表:
scores = [] with open("scores.txt", "r") as f: for line in f: name, score = line.strip().split() scores.append( (name, int(score)) )
写入多个值
同样分两种场景:
- 写入纯数值
values = [100, 200, 300, 400, 500] with open("data.txt", "w") as f: # 把数值转成字符串,用空格分隔后写入一行 f.write(" ".join(map(str, values)) + "\n")
- 写入带名字的分数(逐行)
scores = [("Alice", 95), ("Bob", 88), ("Charlie", 92)] with open("scores.txt", "w") as f: for name, score in scores: f.write(f"{name} {score}\n")
二、实现高分榜读写功能(对应你的C++需求)
你的C++代码是要维护前5名的高分榜,包含名字和分数,Python可以完美复刻这个逻辑,而且代码更简洁。下面是完整可运行的实现:
1. 加载现有高分榜
如果文件不存在,自动初始化5个默认条目:
def load_high_scores(): high_scores = [] try: with open("High_Scores.txt", "r") as f: for _ in range(5): line = f.readline().strip() if not line: # 空行用默认值填充 high_scores.append(("Unknown", 0)) else: name, score = line.split() high_scores.append( (name, int(score)) ) except FileNotFoundError: # 文件不存在时初始化5个默认高分 high_scores = [("Unknown", 0) for _ in range(5)] return high_scores
2. 保存更新后的高分榜
def save_high_scores(high_scores): with open("High_Scores.txt", "w") as f: for name, score in high_scores: f.write(f"{name} {score}\n")
3. 检查并更新高分榜
当玩家获得新分数时,判断是否能挤入前5,然后插入到对应位置,移除最后一名:
def update_high_scores(new_name, new_score): high_scores = load_high_scores() # 找新分数的插入位置 insert_pos = 5 for i in range(5): if new_score > high_scores[i][1]: insert_pos = i break if insert_pos < 5: # 插入新分数,移除最后一个保持5个条目 high_scores.insert(insert_pos, (new_name, new_score)) high_scores.pop() save_high_scores(high_scores) print(f"恭喜{new_name}!进入高分榜第{insert_pos+1}名!") else: print(f"很遗憾{new_name},你的分数{new_score}未能进入高分榜")
4. 测试使用(程序启动时的流程)
# 程序启动时读取并显示高分榜 print("=== 当前高分榜 ===") high_scores = load_high_scores() for rank, (name, score) in enumerate(high_scores, 1): print(f"第{rank}名:{name} - {score}分") # 模拟玩家获得新分数 update_high_scores("Tom", 150) update_high_scores("Jerry", 120) # 再次显示更新后的榜单 print("\n=== 更新后的高分榜 ===") high_scores = load_high_scores() for rank, (name, score) in enumerate(high_scores, 1): print(f"第{rank}名:{name} - {score}分")
补充说明
和你之前的C代码相比,Python的with语句自动处理文件的打开和关闭,不用手动调用close();用try-except处理文件不存在的异常,比C的ifstream判断更直观。
内容的提问来源于stack exchange,提问作者NeverEndingCycle
相关产品推荐
相关产品推荐

