csv Golang函数无法正确阅读文件名

a0zr77ik  于 9个月前  发布在  Go
关注(0)|答案(2)|浏览(99)

所以,我有一个仓库,里面有几个.csv文件,它们包含数据库的表模式。我写了一个Golang代码,从仓库中获取文件名列表,然后打开这些文件,读取内容并创建一个MySQL CREATE查询。
我面临的问题是,对于某些.csv文件,Golang代码最终会阅读错误的标题,这会在后面的阶段引起问题。例如,有一些文件的名称- config_hr.csv,config_oe.csv,contribution_analysis.csv被读取为onfig_hr.csv,onfig_oe.csv,onfig_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)
        }

字符串

e0bqpujr

e0bqpujr1#

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")

sdnqo3pr

sdnqo3pr2#

这不是一个编码问题,这是一个strings.Trim的问题。strings.Trim将从开始和结束使用一个割集,而不是一个字符串。所以你的“.csv”本质上是说“如果这个集中的东西是在字符串的开头或结尾,剪切它。如果你的文件名为svconfig_oe.csv,你会遇到同样的问题-你会以onfig_oe结束。
您可以使用strings.TrimRight(仍然是割集,但仅限于字符串的结尾),或者因为您知道文件以.csv结尾,所以只需再次使用strings.Replace与“.csv”-在这种情况下,strings.Replace将查找确切的字符串而不是割集。

相关问题