2018-04-27 04:32
浏览 125

文件名,目录名或卷标签语法不正确-尝试在Go lang中读取文件时

I want to read contents of text file.

When I am passing the file name as string like this:

stream, err = ioutil.ReadFile("sample.txt")

its working. Its even working if do in this way:

filename := "sample.txt"
stream, err = ioutil.ReadFile(filename)

But when I get the value of filename from string array, it fails to get the file and throw the error: The filename, directory name, or volume label syntax is incorrect

filename := lines[1] //where lines[] is an array of strings
stream, err = ioutil.ReadFile(filename)

Debug information

", lines[1]) // output: mytext2.txt

图片转代码服务由CSDN问答提供 功能建议



  stream,err = ioutil.ReadFile(“ sample.txt”  )

可以正常工作。 甚至可以这样工作:

 文件名:=“样本 .txt“ 
stream,err = ioutil.ReadFile(filename)

但是当我从字符串数组中获取filename的值时,它无法获取文件,并且 引发错误: 文件名,目录名称或卷标签语法不正确

 文件名:=行[1  ] //其中lines []是字符串数组
stream,err = ioutil.ReadFile(filename)

”,lines [1])//输出:mytext2.txt 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyi3767 2018-04-27 10:47

    The application should trim the from the end of the string using strings.TrimSuffix(filename, "") or strings.TrimSpace(filename).

    If OP used strings.Split(s, " ", -1) to create lines, then the trailing can also be avoided by splitting on " " instead.

    点赞 打赏 评论

相关推荐 更多相似问题