Directory

Inherits: Reference < Object

Tipo utilizado para manejar el sistema de archivos.

Descripción

Directory type. It is used to manage directories and their content (not restricted to the project folder).

When creating a new Directory, its default opened directory will be res://. This may change in the future, so it is advised to always use open to initialize your Directory where you want to operate, with explicit error checking.

Note: Many resources types are imported (e.g. textures or sound files), and their source asset will not be included in the exported game, as only the imported version is used. Use ResourceLoader to access imported resources.

Here is an example on how to iterate through the files of a directory:

func dir_contents(path):
    var dir = Directory.new()
    if dir.open(path) == OK:
        dir.list_dir_begin()
        var file_name = dir.get_next()
        while file_name != "":
            if dir.current_is_dir():
                print("Found directory: " + file_name)
            else:
                print("Found file: " + file_name)
            file_name = dir.get_next()
    else:
        print("An error occurred when trying to access the path.")

Tutoriales

Métodos

Error

change_dir ( String todir )

Error

copy ( String from, String to )

bool

current_is_dir ( ) const

bool

dir_exists ( String path )

bool

file_exists ( String path )

String

get_current_dir ( )

int

get_current_drive ( )

String

get_drive ( int idx )

int

get_drive_count ( )

String

get_next ( )

int

get_space_left ( )

Error

list_dir_begin ( bool skip_navigational=false, bool skip_hidden=false )

void

list_dir_end ( )

Error

make_dir ( String path )

Error

make_dir_recursive ( String path )

Error

open ( String path )

Error

remove ( String path )

Error

rename ( String from, String to )

Descripciones de Métodos

Cambia el directorio actualmente abierto por el que se pasa como argumento. El argumento puede ser una ruta relativa al directorio actual (por ejemplo, newdir o ../newdir), o una ruta absoluta (por ejemplo, /tmp/newdir o res://somedir/newdir).

Devuelve una de las constantes del código Error o si tiene éxito OK.


Copia el archivo from al destino to. Ambos argumentos deben ser rutas de acceso a los archivos, ya sea relativas o absolutas. Si el archivo de destino existe y no está protegido contra el acceso, será sobrescrito.

Devuelve una de las constantes del código Error o en caso de éxito OK.


  • bool current_is_dir ( ) const

Devuelve si el objeto actual procesado con la última llamada a get_next es un directorio. . y .. son considerados directorios.


Returns whether the target directory exists. The argument can be relative to the current directory, or an absolute path.


Returns whether the target file exists. The argument can be relative to the current directory, or an absolute path.


Returns the absolute path to the currently opened directory (e.g. res://folder or C:\tmp\folder).


  • int get_current_drive ( )

Devuelve el índice de la unidad de disco del directorio abierto actualmente. Vea get_drive para convertir el índice devuelto al nombre de la unidad.


On Windows, returns the name of the drive (partition) passed as an argument (e.g. C:).

On macOS, returns the path to the mounted volume passed as an argument.

On Linux, returns the path to the mounted volume or GTK 3 bookmark passed as an argument.

On other platforms, or if the requested drive does not exist, the method returns an empty String.


  • int get_drive_count ( )

On Windows, returns the number of drives (partitions) mounted on the current filesystem.

On macOS, returns the number of mounted volumes.

On Linux, returns the number of mounted volumes and GTK 3 bookmarks.

On other platforms, the method returns 0.


Devuelve el siguiente elemento (archivo o directorio) en el directorio actual (incluyendo . y .., a menos que skip_navigational haya sido dado a list_dir_begin).

Se devuelve el nombre del archivo o directorio (y no su ruta completa). Una vez que la secuencia se ha procesado completamente, el método devuelve una cadena vacía y cierra la secuencia automáticamente (es decir, list_dir_end no sería obligatorio en tal caso).


  • int get_space_left ( )

En los sistemas de escritorio UNIX, devuelve el espacio disponible en el disco del directorio actual. En otras plataformas, esta información no está disponible y el método devuelve 0 o -1.


  • Error list_dir_begin ( bool skip_navigational=false, bool skip_hidden=false )

Initializes the stream used to list all files and directories using the get_next function, closing the currently opened stream if needed. Once the stream has been processed, it should typically be closed with list_dir_end.

If skip_navigational is true, . and .. are filtered out.

If skip_hidden is true, hidden files are filtered out.


  • void list_dir_end ( )

Closes the current stream opened with list_dir_begin (whether it has been fully processed with get_next does not matter).


Crea un directorio. El argumento puede ser relativo al directorio actual, o una ruta absoluta. El directorio de destino debe colocarse en un directorio ya existente (para crear la ruta completa de forma recursiva, véase make_dir_recursive).

Devuelve una de las constantes de código de Error (OK en el éxito).


Crea un directorio de destino y todos los directorios intermedios necesarios en su camino, llamando a make_dir recursivamente. El argumento puede ser relativo al directorio actual, o un camino absoluto.

Devuelve una de las constantes de código de Error (OK en el éxito).


Opens an existing directory of the filesystem. The path argument can be within the project tree (res://folder), the user directory (user://folder) or an absolute path of the user filesystem (e.g. /tmp/folder or C:\tmp\folder).

Returns one of the Error code constants (OK on success).


Borra el archivo de destino o un directorio vacío. El argumento puede ser relativo al directorio actual, o una ruta absoluta. Si el directorio de destino no está vacío, la operación fallará.

Devuelve una de las constantes del código Error (OK en caso de éxito).


Renames (move) the from file or directory to the to destination. Both arguments should be paths to files or directories, either relative or absolute. If the destination file or directory exists and is not access-protected, it will be overwritten.

Returns one of the Error code constants (OK on success).