Python读写txt文件存储列表方法 解决pygame项目IndexError报错
问题根因
你当前的实现存在两处核心错误:
- 写入阶段用
"".join(map(str, circles))拼接内容,会直接把每个子列表的字符串形式拼在一起,丢失元素间的逗号、外层列表的方括号,最终写入的内容不是合法的Python数据结构表达式 - 读取阶段直接把读取到的整段字符串套入列表,得到的是只有1个字符串元素的列表,后续代码按嵌套列表规则访问
circle[2]、circle[0][0]这类索引时,实际是在访问字符串的索引,自然触发IndexError报错
解决方案
方案1:ast.literal_eval实现明文txt存储(最适配需求)
该方案是Python官方推荐的安全结构转译方案,不会执行恶意代码,存储的文件为可直接查看的明文txt,改动手脚最少。
改动点:
- 代码顶部新增导入
import ast - 写入逻辑改为直接将整个列表转为字符串写入
- 读取逻辑用
ast.literal_eval将字符串还原为原始嵌套列表
关键代码示例
写入部分:
if keys[pygame.K_s]: with open("myfile.txt", "w", encoding="utf-8") as f: f.write(str(circles))
读取部分:
if keys[pygame.K_o]: with open("myfile.txt", "r", encoding="utf-8") as f: content = f.read() circles = ast.literal_eval(content)
改后完整代码
import pygame import os import ast pygame.init() pen_color = (255, 255, 255) WIDTH = 1000 HEIGHT = 1000 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) # COLORS GREEN_IMG = pygame.image.load(os.path.join("Colors", "green.png")) GREEN = pygame.transform.scale(GREEN_IMG, (50, 50)) pen_size = 10 circles = [] def draw_colors(): global pen_color WIN.blit(GREEN, (900, 900)) mouse = pygame.mouse.get_pos() mouse_pressed = pygame.mouse.get_pressed() if mouse_pressed[0]: if 900 <= mouse[0] <= 950 and 900 <= mouse[1] <= 950: pen_color = (0, 255, 0) def handle_drawing(): mouse_pressed = pygame.mouse.get_pressed() if mouse_pressed[0]: mouse_pos = pygame.mouse.get_pos() circles.append([mouse_pos, pen_size, pen_color]) for circle in circles: pygame.draw.circle(WIN, circle[2], (circle[0][0], circle[0][1]), circle[1]) def key_control(): global pen_size global circles keys = pygame.key.get_pressed() if keys[pygame.K_b]: pen_size += 1 if keys[pygame.K_s]: with open("myfile.txt", "w", encoding="utf-8") as f: f.write(str(circles)) if keys[pygame.K_o]: with open("myfile.txt", "r", encoding="utf-8") as f: content = f.read() circles = ast.literal_eval(content) def main(): clock = pygame.time.Clock() while True: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return key_control() handle_drawing() draw_colors() pygame.display.update() main()
方案2:json模块存储
跨语言通用的明文存储方案,不需要手动处理格式,稳定性更高。
关键代码示例
顶部新增导入import json
写入部分:
if keys[pygame.K_s]: with open("myfile.txt", "w", encoding="utf-8") as f: json.dump(circles, f)
读取部分:
if keys[pygame.K_o]: with open("myfile.txt", "r", encoding="utf-8") as f: circles = json.load(f)
方案3:pickle模块序列化
Python专属的序列化方案,支持所有Python原生数据结构,不需要处理格式兼容问题,存储为二进制文件。
关键代码示例
顶部新增导入import pickle
写入部分:
if keys[pygame.K_s]: with open("myfile.pkl", "wb") as f: pickle.dump(circles, f)
读取部分:
if keys[pygame.K_o]: with open("myfile.pkl", "rb") as f: circles = pickle.load(f)
内容的提问来源于stack exchange,提问作者Timo 42
相关产品推荐
相关产品推荐

