
本文详解 kivy 应用中因 `readline()` 自动保留 `n` 而引发的文本错位问题,提供安全读写文件的标准实践,包括自动去除换行符、统一写入逻辑及异常防护建议。
在 Kivy 等 GUI 应用中,文件读写看似简单,但极易因换行符(n)处理不当导致数据失真——正如你遇到的问题:readline() 读取时会原样包含末尾的换行符,而 TextInput.text 将 n 渲染为实际换行;当再次用 f.write(text + “n”) 保存时,若原文本已含 n,就会产生多余空行,造成循环性格式污染。
✅ 正确做法:读取时剥离换行符,写入时统一控制
修改 on_start() 方法,使用 .rstrip(‘n’) 安全移除可能存在的换行符(推荐 rstrip() 而非 strip(),避免误删首尾空格):
def on_start(self): _ids = self.sm.get_screen("Screeen").ids try: with open("settings.txt", "r", encoding="utf-8") as f: for attr in "abc": line = f.readline() _ids[attr].text = line.rstrip('n') if line else "" except FileNotFoundError: # 首次运行时 settings.txt 不存在,留空即可 pass except Exception as e: print(f"读取配置文件失败: {e}")
同时优化 on_stop(),避免重复添加 n 导致空行累积:
def on_stop(self): try: with open("settings.txt", "w", encoding="utf-8") as f: for attr in "abc": text = self.sm.get_screen("Screeen").ids[attr].text f.write(text + "n") # 每行显式写入 n,确保格式一致 except Exception as e: print(f"保存配置文件失败: {e}")
⚠️ 关键注意事项
- 始终指定 encoding=”utf-8″:避免跨平台(windows/linux/macOS)换行符(rn vs n)和中文乱码问题;
- readline() 返回空字符串 “” 表示 EOF:需判断 if line 防止对空行赋值;
- 不要依赖 f.close() 手动关闭:with 语句已确保资源自动释放;
- 首次启动时文件可能不存在:用 try/except FileNotFoundError 容错,而非假设文件一定存在;
- 若需更健壮配置管理,可考虑 json 格式替代纯文本,天然支持多行、特殊字符与结构化数据:
# 示例:改用 jsON(推荐进阶场景) import json def on_start(self): try: with open("settings.json", "r", encoding="utf-8") as f: data = json.load(f) _ids = self.sm.get_screen("Screeen").ids _ids.a.text = data.get("a", "") _ids.b.text = data.get("b", "") _ids.c.text = data.get("c", "") except (FileNotFoundError, json.JSONDecodeError): pass def on_stop(self): data = { "a": self.sm.get_screen("Screeen").ids.a.text, "b": self.sm.get_screen("Screeen").ids.b.text, "c": self.sm.get_screen("Screeen").ids.c.text, } with open("settings.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)
遵循以上实践,即可彻底解决因换行符导致的“多出空行”问题,让配置文件读写稳定、可预测、跨平台兼容。
立即学习“Python免费学习笔记(深入)”;