go语言列出文件夹下文件夹_使用Go列出文件夹中的文件

本文详细介绍了如何使用Go的Walk、ReadDir和Readdir函数来遍历文件系统,获取文件夹内的文件列表。通过示例代码展示了如何根据需求过滤文件和子目录,以及如何获取文件的详细信息。
摘要由CSDN通过智能技术生成

go语言列出文件夹下文件夹

In this article I explain how to get a list of files inside a folder on the filesystem, a task also called tree traversing, with Go.

在本文中,我解释了如何使用Go获取文件系统上的文件夹内的文件列表,该任务也称为树遍历

There are two handy stdlib functions that you can use depending on your goal.

您可以根据自己的目标使用两个方便的stdlib函数。

I list 3 ways: using filepath.Walk, ioutil.ReadDir or os.File.Readdir.

我列出了3种方法:使用filepath.Walkioutil.ReadDiros.File.Readdir

使用filepath.Walk (Using filepath.Walk)

The path/filepath stdlib package provides the handy Walk function. It automatically scans subdirectories, though, so make sure this is what you actually want.

path/filepath stdlib软件包提供了便捷的Walk功能。 但是,它会自动扫描子目录,因此请确保这是您真正想要的。

Usage is very simple:

用法很简单:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    var files []string

    root := "/some/folder/to/scan"
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        files = append(files, path)
        return nil
    })
    if err != nil {
        panic(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值