Hi,
I have a program that walks through a directory and for every pdf file it founds it does some action, but I am not sure why it is executing this action twice.
Might it be because when it finds the file “.”, which in linux is the current directory, it starts over? Is there any way to avoid this?
Here’s an example based on my previous response. Note that info is an os.FileInfo object so you get information such as modtime, size, whether it’s a directory, it’s name, mode and more:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// Walk recursively starting at the current directory.
filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Printf("Path: %s, Size: %d, ModTime: %v\n", path, info.Size, info.ModTime())
return nil
})
}
By the looks of it, whatever sftp package you are using seems to be using the kr/fs package underneath, so can you try replacing your loop with this and let me know what the output is:
for w.Step() {
if err := w.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
if filepath.Ext(w.Path()) == ".pdf" {
fmt.Println(w.Path())
}
}
Just by the way, you definitely don’t need to be using regular expressions for something as simple as checking an extension. I would personally just use filepath.Ext like in the above example.
You’ll need to import path/filepath and os for the above example to work. (Not sure how much Go you’ve done, but just specifying incase you are very new )
My assumption was that you probably had a second file that you were unaware of so that’s why I thought printing the full paths of the found pdf’s might help