Golang函數無法正確讀取檔案名
所以,我有一個包含多個 .csv 檔案的儲存庫,它們包含資料庫的表格架構。我編寫了一段 Golang 程式碼,它從儲存庫中取得文件名稱列表,然後打開這些文件,讀取內容並建立 MySQL CREATE 查詢。
我面臨的問題是,對於某些 .csv 文件,Golang 程式碼最終會錯誤地讀取標題,這會導致後期出現問題。例如,有一些名為 config_hr.csv、config_oe.csv、contribution_analysis.csv 的檔案被讀取為 onfig_hr.csv、onfig_oe.csv、ontribution_analysi.csv。如果我將名稱大寫,這個問題似乎可以解決,但是在我們專案的後期階段還會出現許多其他問題。
這是某種程式設計問題嗎?我已經檢查了 Windows、Mac 和 Linux 上的程式碼,Golang 版本是最新的 v1.21,任何幫助或見解將不勝感激!
讀取 CSV 檔案名稱的 Golang 程式碼片段
entries, err := FileEntry.Readdir(0) if err != nil { log.Fatal(err) } // Now, open all the files one by one, and extract the content of the files. // Then modify the resultant string to be of MySQL compatibility. for _, e := range entries { // Mimicking the SQL Query of Table Creation query. Query_String := ("CREATE TABLE IF NOT EXISTS " + strings.ToLower(strings.Trim(strings.Replace(e.Name(), " ", "_", -1), ".csv")) + " (\n") fmt.Println("Opening -- " + file_folder + "/" + e.Name()) file, err := os.Open(file_folder + "/" + e.Name()) if err != nil { log.Fatal(err) } defer file.Close() // Reading the CSV file from path. reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { log.Fatal(err) }
正確答案
將 string.Trim
函數替換為下列函數。
// getFileNameWithoutExtension takes a file path as input and returns // the file name without its extension. It utilizes the filepath package // to extract the base name and then removes the extension. func getFileNameWithoutExtension(filePath string) string { // Get the base name of the file path (including extension) baseName := filepath.Base(filePath) // Calculate the length to remove the extension from the base name // and obtain the file name without extension fileNameWithoutExtension := baseName[:len(baseName)-len(filepath.Ext(baseName))] // Return the file name without extension return fileNameWithoutExtension }
範例程式碼:
Query_String := ("CREATE TABLE IF NOT EXISTS " + strings.ToLower(getFileNameWithoutExtension(strings.Replace(e.Name(), " ", "_", -1))) + " (\n")
以上是Golang函數無法正確讀取檔案名的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在Go語言中,調用結構體方法需先定義結構體和綁定接收者的方法,使用點號訪問。定義結構體Rectangle後,可通過值接收者或指針接收者聲明方法;1.使用值接收者如func(rRectangle)Area()int,通過rect.Area()直接調用;2.若需修改結構體,應使用指針接收者如func(r*Rectangle)SetWidth(...),Go會自動處理指針與值的轉換;3.嵌入結構體時,內嵌結構體的方法會被提升,可直接通過外層結構體調用;4.Go無需強制使用getter/setter,字

在Go語言中,接口是一種定義行為而不指定實現方式的類型。接口由方法簽名組成,任何實現這些方法的類型都自動滿足該接口。例如,定義一個Speaker接口包含Speak()方法,則所有實現該方法的類型均可視為Speaker。接口適用於編寫通用函數、抽象實現細節和測試中使用mock對象。定義接口使用interface關鍵字並列出方法簽名,無需顯式聲明類型實現了接口。常見用例包括日誌、格式化、不同數據庫或服務的抽象,以及通知系統等。例如,Dog和Robot類型均可實現Speak方法,並傳遞給同一個Anno

TOIntegrategolangServicesWithExistingPypythoninFrasture,userestapisorgrpcForinter-serviceCommunication,允許GoandGoandPyThonAppStoStoInteractSeamlessSeamLlyThroughlyThroughStandArdArdAdrotized Protoccols.1.usererestapis(ViaFrameWorkslikeSlikeSlikeGiningOandFlaskInpyThon)Orgrococo(wirs Propococo)

Go的time包提供了處理時間和持續時間的功能,包括獲取當前時間、格式化日期、計算時間差、處理時區、調度和休眠等操作。要獲取當前時間,使用time.Now()獲取Time結構體,並可通過Year()、Month()、Day()等方法提取具體時間信息;通過Format("2006-01-0215:04:05")可將時間格式化為字符串;計算時間差時,用Sub()或Since()獲取Duration對象,再通過Seconds()、Minutes()、Hours()轉換為對應單位;添

Ingo,ifstatementSexecuteCodeBasedonConconditions.1.BasicsStructurerunsablockifaconditionistrue,例如IFX> 10 {...}。 2.Elseclausehan dlesfalseconditions,例如,else {...}。 3。 elseifchainsmultipleconditions,例如,elseifx == 10 {...}。 4.variableInitializationInsideIndifif,l

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Gohandlesconcurrencyusinggoroutinesandchannels.1.GoroutinesarelightweightfunctionsmanagedbytheGoruntime,enablingthousandstorunconcurrentlywithminimalresourceuse.2.Channelsprovidesafecommunicationbetweengoroutines,allowingvaluestobesentandreceivedinas

在Go中保護臨界區的標準方法是使用sync.Mutex的Lock()和Unlock()方法。 1.聲明一個mutex並將其與要保護的數據一起使用;2.在進入臨界區前調用Lock(),確保只有一個goroutine能訪問共享資源;3.使用deferUnlock()確保鎖始終被釋放,避免死鎖;4.盡量縮短臨界區內的操作以提高性能;5.對於讀多寫少的場景,應使用sync.RWMutex,通過RLock()/RUnlock()進行讀操作,通過Lock()/Unlock()進行寫操作,從而提升並發效率。
