You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言读取文件报错:文件名、目录名或卷标语法不正确

Fixing ioutil.ReadFile Error When Using Filenames from String Arrays

Ah, I’ve been stuck on this exact issue before—those hidden whitespace characters are such a pain! The error you’re seeing ("The filename, directory name, or volume label syntax is incorrect") is a dead giveaway that the string you’re passing as a filename has invisible invalid characters you can’t spot at first glance.

Here’s what you need to do to fix it:

  • Trim whitespace from the filename: When you read lines into a string array (like with bufio.Scanner), each line usually includes a trailing newline (\n) or carriage return (\r on Windows). Even if lines[1] looks like "sample.txt", it might actually be "sample.txt\n" which isn’t a valid filename. Use strings.TrimSpace() to clean it up:
    import "strings"
    
    // ...
    
    filename := strings.TrimSpace(lines[1])
    stream, err := ioutil.ReadFile(filename)
    
  • Inspect the raw string: To see exactly what’s in that string, print it with escaped characters using %q:
    fmt.Printf("Filename content: %q\n", lines[1])
    
    If you see output like "sample.txt\r\n", the \r or \n is the problem.
  • Double-check the array index: Make sure lines[1] is actually the element you think it is. Sometimes when reading files, the first line (index 0) might be empty or a header, so you could be grabbing the wrong line entirely. Print the full array to verify:
    fmt.Println("All lines:", lines)
    
  • Watch for invalid characters: Windows filenames can’t have characters like :, *, ?, ", <, >, |. If your string array comes from external input, these might have snuck in without you noticing.

Quick side note: If you’re using Go 1.16 or later, ioutil.ReadFile is deprecated. You should switch to os.ReadFile instead—it works exactly the same way but is actively maintained.

Give those steps a try—trimming the whitespace is almost certainly going to solve your problem!

内容的提问来源于stack exchange,提问作者Varun Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:29