首页 > 后端开发 > Golang > 正文

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

PHPz
发布: 2024-02-06 11:18:03
转载
1337人浏览过

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 代码片段

小绿鲸英文文献阅读器
小绿鲸英文文献阅读器

英文文献阅读器,专注提高SCI阅读效率

小绿鲸英文文献阅读器 199
查看详情 小绿鲸英文文献阅读器

立即学习go语言免费学习笔记(深入)”;

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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号