首頁 > 後端開發 > Golang > 主體

Golang函數無法正確讀取檔案名

PHPz
發布: 2024-02-06 11:18:03
轉載
1218 人瀏覽過

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中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!