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

如何使用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条)

报告相同问题?

悬赏问题

  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题