使用 Go 检查目录中是否不存在文件扩展名

我正在尝试检查目录是否没有带有“.rpm”扩展名的文件。我不会事先知道文件名是什么,每个目录都会有多个文件。


这是我的代码:


import {

    "fmt"

    "os"

    "path/filepath"

}


func main() {

    dirname := "." + string(filepath.Separator)


    d, err := os.Open(dirname)

    if err != nil {

        fmt.Println(err)

        os.Exit(1)

    }

    defer d.Close()


    files, err := d.Readdir(-1)

    if err != nil {

        fmt.Println(err)

        os.Exit(1)

    }


    fmt.Print("\n" + "Reading " + dirname)


    for _, file := range files {

        if file.Mode().IsRegular() {

            // TODO: if rpm file not present, print no rpm file found

            if filepath.Ext(file.Name()) == ".rpm" {

                fmt.Println(file.Name() + "\n")

                f, err := os.Open(file.Name())

                if err != nil {

                    panic(err)

                }

            }

        }

    }

}

上面的代码将打开当前目录中的所有 .rpm 文件。


我要检查以下内容:如果“.rpm”文件不存在当前目录的文件列表,则打印“rpm 不存在”和 os.Exit。


我试过这段代码:


if filepath.Ext(file.Name()) != ".rpm" {

    fmt.Println("no rpm found")

}

我试过使用


if filepath.Ext(file.Name()) == ".rpm" {

    ... *code above* ...

} else {

    fmt.Println("ERR: RPM file does not exist")

}

我遇到了错误,如果存在其他文件而没有.rpm的扩展名,那么它将提示错误。


如果事先没有文件名,我怎么能这样做?


摇曳的蔷薇
浏览 170回答 2
2回答

弑天下

试试这个...splitted := strings.Split(file.Name(), ".")lenSplit := len(splitted)if lenSplit > 1 && splitted[lenSplit-1] == "rpm" {  // file with extension}...用“.”分割文件名转到字符串数组中的最后一个字符串检查最后一个字符串是否匹配“rpm”

繁花如伊

.rpm在任何一次迭代中都无法判断是否没有文件具有扩展名。您只能在检查所有文件后才能确定。因此,与其尝试将其压缩到循环中,不如维护一个found变量,您可以在.rpm找到文件时对其进行更新。found := false // Assume false for nowfor _, file := range files {    if file.Mode().IsRegular() {        if filepath.Ext(file.Name()) == ".rpm" {            // Process rpm file, and:            found = true        }    }}if !found {    fmt.Println("rpm file not found")}如果您只需要处理 1 个.rpm文件,则不需要“状态”管理(found变量)。如果你找到并处理了一个.rpm文件,你可以返回,如果你到达循环的结尾,你会知道没有任何rpm文件:for _, file := range files {    if file.Mode().IsRegular() {        if filepath.Ext(file.Name()) == ".rpm" {            // Process rpm file, and:            return        }    }}// We returned earlier if rpm was found, so here we know there isn't any:fmt.Println("rpm file not found")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go