douzhuiqiu4923 2019-03-12 15:42
浏览 738
已采纳

如何使用Go编程语言对文件名进行排序?

In my Go project, I need to sort the .json files and to display their name on the terminal when I'm running this command on the terminal go run main.go.

I coded a program which displays all the files in the folder, but I need to sort the .json file.

My code is the following :

package main

import (
    "fmt"
    "log"
    "os"
    "bytes"
    "io"
)

func main() {

    if os.Args[1] == "display-json-name" {
        //reads the directory name and returns a list of directory entries
        dirname := "." 

        f, err := os.Open(dirname)
        if err != nil {
            log.Fatal(err)
        }
        files, err := f.Readdir(-1)
        f.Close()
        if err != nil {
            log.Fatal(err)
        }

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

How can we sort just the different .json files?

And the hierarchy of my project is : enter image description here

  • 写回答

2条回答 默认 最新

  • dongmen5867 2019-03-12 17:21
    关注

    Based on comments, it appears that the question is "How to print files where the file has a .json extension". Here's the code:

    if os.Args[1] == "display-json-name" {
        //reads the directory name and returns a list of directory entries
        dirname := "."
    
        f, err := os.Open(dirname)
        if err != nil {
            log.Fatal(err)
        }
        files, err := f.Readdir(-1)
        f.Close()
        if err != nil {
            log.Fatal(err)
        }
    
        for _, file := range files {
            if filepath.Ext(file.Name()) == ".json" {
                fmt.Println(file.Name())
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • doureng1083 2019-03-12 16:04
    关注

    https://golang.org/pkg/io/ioutil/#ReadDir

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
    )
    
    func main() {
        files, err := ioutil.ReadDir(".")
        if err != nil {
            log.Fatal(err)
        }
    
        for _, file := range files {
            fmt.Println(file.Name())
        }
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 字符串的比较老是报错
  • ¥15 复杂表达式求值程序里的函数优先级问题
  • ¥15 求密码学的客成社记ji着用
  • ¥35 POI导入树状结构excle
  • ¥15 初学者c语言题目解答
  • ¥15 div editable中的光标问题
  • ¥15 mysql报错1415Not allowed to return a result set from a trigger 不知如何修改
  • ¥60 Python输出Excel数据整理,算法较为复杂
  • ¥15 回答几个问题 关于数据库
  • ¥15 51单片机串口通信问题,未完成且要修改