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 (\ron Windows). Even iflines[1]looks like "sample.txt", it might actually be "sample.txt\n" which isn’t a valid filename. Usestrings.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:
If you see output likefmt.Printf("Filename content: %q\n", lines[1])"sample.txt\r\n", the\ror\nis 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.ReadFileis deprecated. You should switch toos.ReadFileinstead—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
相关产品推荐
相关产品推荐

