英文:
How to iterate a directory without entering into subdirectories
问题
假设我有以下的目录结构:
RootDir
---SubDir1
------SubSubDir
---------file1
---------file2
---SubDir2
---SubDir3
---file3
---file4
我想要遍历RootDir目录下的内容(SubDir1、Subdir2、Subdir3、file3、file4),并检查它是一个目录还是一个文件,而不进入子目录,就像filepath.Walk函数所做的那样。
在Go语言库中有没有办法做到这一点?
编辑:
files, err := os.Open("c:\\Documents")
file, err := files.Readdir(0)
if err != nil {
    fmt.Printf("Error: %s\n", err)
}
for f := range file {
    fmt.Println(f.IsDir())
}
在这里,我试图遍历FileInfo,它是一个切片,并检查每个文件是否是一个目录,但我总是得到以下错误:
f.IsDir未定义(类型int没有IsDir字段或方法)
英文:
Lets say I have the following directory structure:
RootDir
---SubDir1
------SubSubDir
---------file1
---------file2
---SubDir2
---SubDir3
---file3
---file4
I want to iterate only over the contents of the RootDir(SubDir1, Subdir2, Subdir3, file3, file 4) and check if it is a dir or a file, without entering into the subdirectories, like filepath.Walk does.
Is there any way to do this in the Go library ?
edit:
files, err := os.Open("c:\\Documents")
file, err := files.Readdir(0)
if err != nil {
	fmt.Printf("Error: %s\n", err)
}
for f := range file {
	fmt.Println(f.IsDir())
}
So here I am trying to iterate trough the FileInfo, which is a slice, and check for every file if it is a directory, but I always get this error:
f.IsDir undefined (type int has no field or method IsDir)
答案1
得分: 2
你可以使用os.Open打开一个目录,并返回一个*os.File对象,该对象具有一个Readdir()方法,用于获取目录中的os.FileInfo对象,而这些FileInfo对象具有一个IsDir()方法。
英文:
You can read a directory by opening it with os.Open and the returned *os.File has a Readdir() method which gives os.FileInfos for the direct folder content and these FileInfo have an IsDir() method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论