Reading Files in GDScript
Our first program will demonstrate reading files in GDScript. Here’s the full source code:
extends Node
func _ready():
# Reading the entire contents of a file into memory
var file = File.new()
if file.open("res://tmp/dat", File.READ) == OK:
var content = file.get_as_text()
print(content)
file.close()
else:
print("Failed to open file")
# For more control over reading, we can use specific methods
if file.open("res://tmp/dat", File.READ) == OK:
# Read some bytes from the beginning of the file
var bytes = file.get_buffer(5)
print("%d bytes: %s" % [bytes.size(), bytes.get_string_from_ascii()])
# Seek to a known location and read from there
file.seek(6)
bytes = file.get_buffer(2)
print("%d bytes @ %d: %s" % [bytes.size(), file.get_position() - bytes.size(), bytes.get_string_from_ascii()])
# Seek relative to current position
file.seek(4, File.SEEK_CUR)
# Seek relative to the end of the file
file.seek(-10, File.SEEK_END)
# There's no direct equivalent to ReadAtLeast, but we can implement similar functionality
file.seek(6)
bytes = file.get_buffer(2)
print("%d bytes @ %d: %s" % [bytes.size(), file.get_position() - bytes.size(), bytes.get_string_from_ascii()])
# Rewind to the beginning of the file
file.seek(0)
# GDScript doesn't have a direct equivalent to bufio, but we can read line by line
var line = file.get_line()
print("First line: %s" % line)
file.close()
else:
print("Failed to open file")
To run the program, save this script as reading_files.gd
and attach it to a Node in your Godot scene. Then, create a file named dat
in the res://tmp/
directory of your Godot project with some content.
When you run the scene, you should see output similar to this:
hello
go
5 bytes: hello
2 bytes @ 6: go
2 bytes @ 6: go
First line: hello
Note that GDScript doesn’t have direct equivalents for all the features shown in the original example, such as bufio
or io.ReadAtLeast
. However, it provides its own set of file reading methods that can accomplish similar tasks.
Also, error handling in GDScript is typically done using if statements to check the result of operations, rather than using exceptions as in some other languages.
Remember to close the file when you’re done with it, which is handled automatically when using the File.close()
method.
Next, we’ll look at writing files in GDScript.