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

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目