第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用 Go 檢查目錄中是否不存在文件擴(kuò)展名

使用 Go 檢查目錄中是否不存在文件擴(kuò)展名

Go
搖曳的薔薇 2022-05-18 14:31:09
我正在嘗試檢查目錄是否沒有帶有“.rpm”擴(kuò)展名的文件。我不會(huì)事先知道文件名是什么,每個(gè)目錄都會(huì)有多個(gè)文件。這是我的代碼: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)                }            }        }    }}上面的代碼將打開當(dāng)前目錄中的所有 .rpm 文件。我要檢查以下內(nèi)容:如果“.rpm”文件不存在當(dāng)前目錄的文件列表,則打印“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")}我遇到了錯(cuò)誤,如果存在其他文件而沒有.rpm的擴(kuò)展名,那么它將提示錯(cuò)誤。如果事先沒有文件名,我怎么能這樣做?
查看完整描述

2 回答

?
弒天下

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊

試試這個(gè)


...

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

lenSplit := len(splitted)

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

  // file with extension

}

...

  1. 用“.”分割文件名

  2. 轉(zhuǎn)到字符串?dāng)?shù)組中的最后一個(gè)字符串

  3. 檢查最后一個(gè)字符串是否匹配“rpm”


查看完整回答
反對(duì) 回復(fù) 2022-05-18
?
繁花如伊

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊

.rpm在任何一次迭代中都無法判斷是否沒有文件具有擴(kuò)展名。您只能在檢查所有文件后才能確定。


因此,與其嘗試將其壓縮到循環(huán)中,不如維護(hù)一個(gè)found變量,您可以在.rpm找到文件時(shí)對(duì)其進(jìn)行更新。


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 個(gè).rpm文件,則不需要“狀態(tài)”管理(found變量)。如果你找到并處理了一個(gè).rpm文件,你可以返回,如果你到達(dá)循環(huán)的結(jié)尾,你會(huì)知道沒有任何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")


查看完整回答
反對(duì) 回復(fù) 2022-05-18
  • 2 回答
  • 0 關(guān)注
  • 174 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)