亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號