Risposte:
// exists returns whether the given file or directory exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return false, err
}
Modificato per aggiungere la gestione degli errori.
panicper una vera "eccezione" come l'oggetto. Puoi "catturare" con una chiamata a recover. errRestituire esplicitamente un come secondo valore restituito è una tecnica Go estremamente idiomatica molto comune. Vedi: golang.org/doc/effective_go.html#errors
if _, err := os.Stat("./conf/app.ini"); err == nil { /*exists*/ } else { /*not exists or some other error*/ }
Puoi usare questo:
if _, err := os.Stat("./conf/app.ini"); err != nil {
if os.IsNotExist(err) {
// file does not exist
} else {
// other error
}
}
Più che altro, visto che mi sono guardato intorno per qualche minuto pensando che la mia domanda fosse una rapida ricerca.
Come verificare se il percorso rappresenta una directory esistente in Go?
Questa è stata la risposta più popolare nei miei risultati di ricerca, ma qui e altrove le soluzioni forniscono solo un controllo dell'esistenza. Per verificare se pathrappresenta una directory esistente, ho scoperto che potrei facilmente:
path := GetSomePath();
if stat, err := os.Stat(path); err == nil && stat.IsDir() {
// path is a directory
}
Parte del mio problema era che mi aspettavo che il path/filepathpacchetto contenga la funzione isDir ().
Modo semplice per verificare se il file esiste o meno:
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
}
fonti:
C'è un modo semplice per verificare se il tuo file esiste o meno:
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
}
}
f, err := os.Open(name)of, err := os.OpenFile(name,os.O_CREATE|os.O_EXCL, mode)e quindi controllareos.IsNotExist(err)).