为什么当我使用错误的文件扩展名尝试打开文本文件时,无法打开它?

huangapple go评论98阅读模式
英文:

Why cant I open a text file when I use the wrong file extension while trying to open it?

问题

我正在尝试使用Go语言读取一个.txt文件,但是我一直被告知程序找不到指定的文件,即使我使用完整的路径也是如此。然而,我现有的代码在读取.go文件时没有问题。

有什么帮助吗?

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)


func main() {
	// 打开输入文件,出错时退出。
	inputFile, err := os.Open("main.go")
	if err != nil {
		log.Fatal("Error opening input file:", err)
	}
	defer inputFile.Close()

	scanner := bufio.NewScanner(inputFile)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(scanner.Err())
	}
}

以上是你提供的代码。

英文:

I'm trying to read a .txt file using Go, but I keep getting told that the program cannot find the specified file, even when I use the complete path to it. However, the code I have has no problem reading .go files.

Help?

package main

import (
"bufio"
"fmt"
"log"
"os"
)


func main() {
// Open an input file, exit on error.
	inputFile, err := os.Open("main.go");
	if err != nil {
		log.Fatal("Error opening input file:", err)
	}
	defer inputFile.Close()
 
	scanner := bufio.NewScanner(inputFile)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(scanner.Err())
	}
}

答案1

得分: 1

你可以在主函数的开头看到你正在添加这段代码:

http://play.golang.org/p/DqnivLi1Z2

cwd, err := os.Getwd()
if err != nil {
	log.Fatal("os.Getwd ", err)
}
log.Println("当前目录", cwd)
files, err := ioutil.ReadDir(cwd)
if err != nil {
	log.Fatal("ioutil.ReadDir", err)
}

for idx, finfo := range files {
	log.Println(idx, " ", finfo.Name)
}
英文:

You can see where you are adding this snippet of code at the beginning of your main function:

http://play.golang.org/p/DqnivLi1Z2

cwd, err := os.Getwd()
if err != nil {
	log.Fatal("os.Getwd ", err)
}
log.Println("Current Directory", cwd)
files, err := ioutil.ReadDir(cwd)
if err != nil {
	log.Fatal("ioutil.ReadDir", err)
}

for idx, finfo := range files {
	log.Println(idx, " ", finfo.Name)
}

huangapple
  • 本文由 发表于 2014年8月19日 06:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/25373297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定