我有个奇怪的问题我有这个CSV
NAME,AGE,CITY
Bob,12,London
James,18,London
Joe,55,Manchester
Simon,21,Manchester和下面的代码。但当我摄取该文件时,它在第一个字段名前有一个空格(如下所示)

下面我尝试了字符串修剪和字符串替换,但都不起作用。有谁有什么想法吗?
func main() {
var files []string
root := "C:\\Users\\kiera\\OneDrive\\Documents\\golang\\df\\filewalk\\csvs"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
files = append(files, path)
return nil
})
if err != nil {
panic(err)
}
for _, file := range files {
//open the file
openfile, _ := ioutil.ReadFile(file)
//cast byte slice as string
contents := string(openfile)
//get rid of whitespace
contents = strings.TrimSpace(contents)
contents = strings.ReplaceAll(contents, " NAME", "NAME")
fmt.Println(contents)
}
}发布于 2020-07-05 04:07:01
如果您使用notepad++、记事本、netbeans等,如果您将文件保存为utf-8,它会在文件的开头添加隐藏字符(BOM)。只需更改IDE或禁用BOM即可。例如,在notepad++中,您可以遵循以下说明https://www.ibm.com/support/pages/how-remove-bom-any-textxml-file
大多数情况下,这个问题都发生在windows中。
https://stackoverflow.com/questions/62733498
复制相似问题