V
V
Vadim Rublev2021-08-27 19:38:43
go
Vadim Rublev, 2021-08-27 19:38:43

Why does the error "The system cannot find the file specified" fire when opening a file?

For some reason, in the block with the ReadDir() function, it cannot open the file. Error ERR_1 is triggered.

filesDir, err := ioutil.ReadDir(DirFiles)
    if err != nil { log.Fatal(err) }
                    
    for _, fileDir := range filesDir {
        if filepath.Ext(fileDir.Name()) == ".html" {
            // Чтение содержимого файла построчно.
            my_File, err := os.Open(fileDir.Name())
                if err != nil {
                    fmt.Println("ERR_1. Ошибка открытия файла:", err)
                    return
                }
                defer my_File.Close()

                var scanner = bufio.NewScanner(my_File)
                ...
        }
    }

Although the same opening of a file in a nearby block of the Walk() function works fine.
Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-08-27
@Vadim Rublev

I suppose that after replacing os.Open(fileDir.Name()) with os.Open(path.Join(DirFiles, fileDir.Name())) everything will work.
I think the problem is here.
Most likely your file structure is close to this
./files/file1
main.go
os.Open tries to open it in the current folder, not in the ./files/ folder, so it can't open it.
And if you pass it to os.Open("./files/file1") - then everything will work (provided that there are rights to it)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question