为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
摇曳的蔷薇 2022-05-18 14:31:09
我正在尝试检查目录是否没有带有“.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的扩展名,那么它将提示错误。如果事先没有文件名,我怎么能这样做?
查看完整描述

2 回答

?
弑天下

TA贡献1818条经验 获得超8个赞

试试这个


...

splitted := strings.Split(file.Name(), ".")

lenSplit := len(splitted)

if lenSplit > 1 && splitted[lenSplit-1] == "rpm" {

  // file with extension

}

...

  1. 用“.”分割文件名

  2. 转到字符串数组中的最后一个字符串

  3. 检查最后一个字符串是否匹配“rpm”


查看完整回答
反对 回复 2022-05-18
?
繁花如伊

TA贡献2012条经验 获得超12个赞

.rpm在任何一次迭代中都无法判断是否没有文件具有扩展名。您只能在检查所有文件后才能确定。


因此,与其尝试将其压缩到循环中,不如维护一个found变量,您可以在.rpm找到文件时对其进行更新。


found := false // Assume false for now

for _, 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")


查看完整回答
反对 回复 2022-05-18
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号