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

如何使用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())
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵