¿Cómo comprobar si existe un archivo o directorio?


Quiero comprobar la existencia de file ./conf/app.ini en mi código Go, pero no puedo encontrar una buena manera de hacerlo.

Sé que hay un método de Archivo en Java: public boolean exists(), que devuelve true si el archivo o directorio existe.

Pero ¿cómo se puede hacer esto en Go?

 93
Author: Tim Cooper, 2012-05-09

5 answers

// exists returns whether the given file or directory exists or not
func exists(path string) (bool, error) {
    _, err := os.Stat(path)
    if err == nil { return true, nil }
    if os.IsNotExist(err) { return false, nil }
    return true, err
}

Editado para agregar manejo de errores.

 152
Author: Mostafa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-08 09:35:23

Puedes usar esto:

if _, err := os.Stat("./conf/app.ini"); err != nil {
    if os.IsNotExist(err) {
        // file does not exist
    } else {
        // other error
    }
}

Véase: http://golang.org/pkg/os/#IsNotExist

 102
Author: Denys Séguret,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-09 06:23:05

Más bien para su información, ya que miré a mi alrededor durante unos minutos pensando que mi pregunta estaría a una búsqueda rápida.

¿Cómo comprobar si path representa un directorio existente en Go?

Esta fue la respuesta más popular en mis resultados de búsqueda, pero aquí y en otros lugares las soluciones solo proporcionan verificación de existencia. Para comprobar si path representa un directorio existente, encontré que podía fácilmente:

path := GetSomePath();
if stat, err := os.Stat(path); err == nil && stat.IsDir() {
    // path is a directory
}

Parte de mi problema era que esperaba que el paquete path/filepath contuviera el isDir() función.

 14
Author: Edward Wagner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-16 04:20:33

Una forma sencilla de comprobar si el archivo existe o no:

if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err) {
    // path/to/whatever does not exist
}

if _, err := os.Stat("/path/to/whatever"); err == nil {
    // path/to/whatever exists
}

Fuentes:

 2
Author: Nikta Jn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 10:42:09

Hay una manera sencilla de comprobar si su archivo existe o no:

if _, err := os.Stat("./conf/app.ini"); err != nil {
    if os.IsNotExist(err) {
        ..... //Shows error if file not exists
    } else {
       ..... // Shows success message like file is there
    }
}
 -1
Author: Kabeer Shaikh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 03:13:48