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

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

问题描述

我一直在想如何在 Go 中简单地列出单个目录中的文件和文件夹.

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

我找到了 filepath.Walk,但它进入了 sub- 目录自动,我不想要.我所有的其他搜索都没有好转.

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.

推荐答案

您可以尝试使用 io/ioutil 包中的 ReadDir 函数.根据文档:

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

ReadDir 读取以 dirname 命名的目录并返回已排序的目录条目列表.

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

生成的切片包含 os.FileInfo 类型,这些类型提供列出的方法 这里.这是一个列出当前目录中所有内容名称的基本示例(包含文件夹但未特别标记 - 您可以使用 IsDir() 方法检查项目是否为文件夹):

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天全站免登陆