Skip to content

Go 语言文件读取与处理

Published: at 07:25 AMSuggest Changes

使用 Go 读取和处理文件

读取文件

Go by Example: Reading Files

Read a file in Go

Go read file

package main

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

func main() {

	f, err := os.Open("list.txt")

	if err != nil {
		log.Fatal(err)
	}

	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			log.Fatalln(err)
		}
	}(f)

	scanner := bufio.NewScanner(f)

	for scanner.Scan() {

		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}

获取当前路径

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    exPath := filepath.Dir(ex)
    fmt.Println(exPath)
}

Previous Post
GoLand: 调整可编辑文件大小
Next Post
Nginx 前端配置与二级路由详解