reading from a file in Godot 4

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By givenmnisi6

I’m writing a method (function to read from a file), and I get this error: Could not find type “File” in the current scope and Identifier “File” not declared in the current scope.

Here is the code :

func loads(num: int) → void:

var poemTitle: RichTextLabel = $Title
var poemText: RichTextLabel = $Text

var txtFile: File =
if !txtFile.file_exists("res://Poems/" + story[iStory] + ".txt"):
	poemText.text = "Story not found"
	return"res://Poems/" + story[iStory] + ".txt", File.READ)
:bust_in_silhouette: Reply From: HyperlinkYourHeart

I don’t think there’s any such class. I think you probably want the FileAccess class instead.

Thank you, I needed this!

givenmnisi6 | 2023-06-12 15:57

Right. The File class from Godot 3.x was replaced by the FileAccess class in Godot 4.x.

jgodfrey | 2023-06-12 16:13

Okay thank you I will look into it. I really appreciate it.

givenmnisi6 | 2023-06-12 16:16

Related, for this (and other) upgrade 3.x to 4.x topics, see this docs page:

Upgrading from Godot 3 to Godot 4 — Godot Engine (stable) documentation in English

jgodfrey | 2023-06-12 17:53

I get this error: Native class “FileAccess” cannot be constructed as it is abstract., Static function “new()” not found in base “FileAccess”.

Here is the code below:

var poemTitle = get_node("Title") as RichTextLabel
var poemText = get_node("Text") as RichTextLabel

var txtFile: FileAccess =

if !txtFile.file_exists("res://Poems/" + story[iStory] + ".txt"):
	poemText.text = "Story not found"
	return"res://Poems/" + story[iStory] + ".txt", FileAccess.READ)

givenmnisi6 | 2023-06-12 17:56

Check the docs linked above by @HyperlinkYourHeart. It contains some very simple examples of a file read operation…

jgodfrey | 2023-06-12 18:00

Okay, I will do so. Thank you so much for the help.

givenmnisi6 | 2023-06-12 18:11