
所以,我有一个包含多个 .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 代码片段
立即学习“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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号