在Go中列出目录 [英] List directory in Go

查看:92
本文介绍了在Go中列出目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我找到了 filepath.Walk ,但它会自动进入子目录,其中I不想要。我所有的其他搜索都没有改变任何事情。

我确定这个功能存在,但它真的很难找到。如果有人知道我应该看哪里,请告诉我。谢谢。

/#ReadDirrel =noreferrer> ReadDir 函数的 io / ioutil 包中。根据文档:


ReadDir读取由dirname命名的目录并返回一个已排序的目录条目列表。


结果切片包含 os.FileInfo 类型,它们提供列出的方法这里。下面是一个基本的例子,列出当前目录中所有内容的名称(包含文件夹但未特别标记 - 您可以通过使用 IsDir()

  package main 

import(
fmt
io / ioutil
log


func main(){
files,err:= ioutil.ReadDir(./)
如果err!= nil {
log.Fatal(err)
}

for _,f:=范围文件{
fmt.Println( f.Name())
}
}


I've been trying to figure out how to simply list the files and folders in a single directory in Go.

I've found filepath.Walk, but it goes into sub-directories automatically, which I don't want. All of my other searches haven't turned anything better up.

I'm sure that this functionality exists, but it's been really hard to find. Let me know if anyone knows where I should look. Thanks.

解决方案

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {
            fmt.Println(f.Name())
    }
}

这篇关于在Go中列出目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆