卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34246本站已运行391

Golang函数无法正确读取文件名

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")
卓越飞翔博客
上一篇: cURL 和 Postman HTTP POST 工作,但 Golang 请求失败,状态为 400
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏