Skip to main content
Version: go

文件夹

import (
"os"
"path/filepath"
"time"
)
// CreateDateDir 根据当前日期来创建文件夹
func CreateDateDir(Path string) string {
folderName := time.Now().Format("20060102")
folderPath := filepath.Join(Path, folderName)
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
// 必须分成两步:先创建文件夹、再修改权限
os.Mkdir(folderPath, 0777) //0777也可以os.ModePerm
os.Chmod(folderPath, 0777)
}
return folderPath
}

os 常用

os.Getwd()   //获取当前目录
f1, _ := os.Create("./1.txt") // 创建文件
defer f1.Close()
os.Remove("abc/d/e/f") // 删除指定目录下所有文件
os.RemoveAll("abc") // 删除指定目录
os.Rename("./2.txt", "./2_new.txt") // 重命名文件

文件

读取

package main
import (
"bufio"
"fmt"
"io"
"os"
)

func main() {
// 打开文件 只读
inputFile, inputError := os.Open("input.dat")

// 错误捕获
if inputError != nil {
fmt.Printf("An error occurred on opening the inputfile\n" +
"Does the file exist?\n" +
"Have you got acces to it?\n")
return // exit the function on error
}

// 关闭文件
defer inputFile.Close()

// 获取读取器
inputReader := bufio.NewReader(inputFile)
for {
// 逐行读取
inputString, readerError := inputReader.ReadString('\n')
fmt.Printf("The input was: %s", inputString)
if readerError == io.EOF {
return
}
}
}

读取整个文件内容

package main
import (
"fmt"
"io/ioutil"
"os"
)

func main() {
inputFile := "products.txt"
outputFile := "products_copy.txt"
// 读取文件
buf, err := ioutil.ReadFile(inputFile)

// error
if err != nil {
fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
// panic(err.Error())
}
fmt.Printf("%s\n", string(buf))

// 写入文件
err = ioutil.WriteFile(outputFile, buf, 0644) // oct, not hex
if err != nil {
panic(err.Error())
}
}

缓冲读取

buf := make([]byte, 1024)
...
n, err := inputReader.Read(buf)
if (n == 0) { break}

列读取

package main
import (
"fmt"
"os"
)

func main() {
// 打开文件
file, err := os.Open("products2.txt")
if err != nil {
panic(err)
}
defer file.Close()

var col1, col2, col3 []string
for {
var v1, v2, v3 string
// 读取文件每一行的某一列
_, err := fmt.Fscanln(file, &v1, &v2, &v3)
// scans until newline
if err != nil {
break
}
// 追加列数据
col1 = append(col1, v1)
col2 = append(col2, v2)
col3 = append(col3, v3)
}

fmt.Println(col1)
fmt.Println(col2)
fmt.Println(col3)
}

写入

package main

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

func main () {
// var outputWriter *bufio.Writer
// var outputFile *os.File
// var outputError os.Error
// var outputString string
// 只写模式打开文件, 文件不存在则创建
outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)

// error
if outputError != nil {
fmt.Printf("An error occurred with file opening or creation\n")
return
}
// 关闭文件
defer outputFile.Close()

// 创建一个写入器
outputWriter := bufio.NewWriter(outputFile)
outputString := "hello world!\n"

for i:=0; i<10; i++ {
// 将字符串写入缓冲区
outputWriter.WriteString(outputString)
}

// 缓冲区完全写入文件
outputWriter.Flush()
}