HOME / 第 6 部分 · 数据与进阶开发 / 第 61 课
MODULE 6 · 数据与进阶开发
第 61 课 · 文件读写
🎯 本课学习目标
- 理解 Godot 文件路径系统
- 用 FileAccess 读写文本文件
- 读写二进制与 CSV
存档、日志、配置都靠文件。本课掌握 Godot 的文件读写。
📖 详细教学步骤
文件路径系统概念
| 前缀 | 含义 |
|---|---|
| res:// | 项目目录(只读,打包后不可写) |
| user:// | 用户数据目录(可写,存档放这里) |
💡 游戏运行时写文件必须用 user://,它在不同平台自动映射到正确位置。
写文本文件代码
FileAccess 打开 + 写入:
GDSCRIPTfunc save_text(path: String, content: String):
var file = FileAccess.open("user://" + path, FileAccess.WRITE)
if file:
file.store_string(content)
file.close() # 记得关闭
print("已保存:", path)
else:
print("打开失败!")
读文本文件代码
读取并处理:
GDSCRIPTfunc load_text(path: String) -> String:
if not FileAccess.file_exists("user://" + path):
return ""
var file = FileAccess.open("user://" + path, FileAccess.READ)
var content = file.get_as_text()
file.close()
return content
逐行读写代码
适合日志、CSV:
GDSCRIPT# 写多行
var file = FileAccess.open("user://log.txt", FileAccess.WRITE)
file.store_line("第1条日志")
file.store_line("第2条日志")
file.close()
# 读多行
var f = FileAccess.open("user://log.txt", FileAccess.READ)
while not f.eof_reached():
var line = f.get_line()
if line != "":
print(line)
f.close()
目录操作代码
创建目录、列文件:
GDSCRIPTDirAccess.make_dir_recursive_absolute("user://saves")
var dir = DirAccess.open("user://")
if dir:
dir.list_dir_begin()
var name = dir.get_next()
while name != "":
if not dir.current_is_dir():
print("文件:", name)
name = dir.get_next()
读游戏内置文件(CSV 配置)实战
读项目内的 CSV 做关卡配置:
GDSCRIPTvar file = FileAccess.open("res://data/enemies.csv", FileAccess.READ)
var lines = file.get_as_text().split("\n")
for line in lines:
var cols = line.split(",")
if cols.size() >= 2:
print("名字:", cols[0], " HP:", cols[1])
⚠️
写文件报错「只读」?
写入路径用了 res://。运行时写入必须用 user://。
⚠️
读文件返回空?
确认路径正确、文件存在;用 FileAccess.file_exists 先判断。
🧪 动手试一试
🏋️ 课后练习
实现一个简单的「游戏日志」:每次运行追加一行时间戳日志,并能在下次启动时打印全部日志。
store_line 追加(WRITE_READ 模式)、get_as_text 读取。
💡
user:// 的存档位置:Windows 在 %APPDATA%\Godot\app_userdata\项目名\。
💡
文件用完务必 close(),防止写入不完整。
🎓 本课小结
res:// 只读项目文件、user:// 可写用户数据;FileAccess.open + store_string/get_as_text 读写;逐行用 store_line/get_line。