Go (3): file folder creation and reading and writing, file copying, conversion and parsing of json and xml

os

os create folder

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	// 创建文件夹
	err := os.Mkdir("example", 0755)
	if err != nil {
    
    
		fmt.Println("文件夹创建失败", err)
		return
	} else {
    
    
		fmt.Println("文件夹创建成功!")
	}
}
package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	// 创建文件夹
	err := os.MkdirAll("example/a/b/c/", 0755)
	if err != nil {
    
    
		fmt.Println("文件夹创建失败", err)
		return
	} else {
    
    
		fmt.Println("文件夹创建成功!")
	}
}

os file read and write

insert image description here

package main

import (
	"fmt"
	"os"
)

func main() {
    
    

	// 创建文件
	file1, err1 := os.Create("test.txt")
	if err1 != nil {
    
    
		fmt.Println("文件创建失败:", err1)
		return
	} else {
    
    
		fmt.Println("文件创建成功!")
	}
	defer file1.Close()

	// 写入文件内容
	n, err2 := file1.Write([]byte("Hello, world!"))
	if err2 != nil {
    
    
		fmt.Println("文件写入失败:", err2)
		return
	} else {
    
    
		fmt.Println("文件写入成功:", n)

		// 打开文件
		file2, err3 := os.Open("test.txt")
		if err3 != nil {
    
    
			fmt.Println("打开文件失败:", err3)
			return
		} else {
    
    
			fmt.Println("打开文件成功!")
		}
		defer file2.Close()

		// 读取文件内容
		buf := make([]byte, 1024)
		n, err4 := file2.Read(buf)
		if err4 != nil {
    
    
			fmt.Println("文件读取失败:", err4)
			return
		} else {
    
    
			content := string(buf[:n])
			fmt.Println("文件读取成功:", content)
		}

	}
}

os to determine whether a file or folder exists

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	// 指定文件或文件夹的路径
	path := "example" // "test.txt"
	// 判断文件或文件夹是否存在
	fileInfo, err := os.Stat(path)
	if err == nil {
    
    
		if fileInfo.IsDir() {
    
    
			fmt.Printf("文件夹 %s 存在\n", path)
		} else {
    
    
			fmt.Printf("文件 %s 存在\n", path)
		}
	} else if os.IsNotExist(err) {
    
    
		fmt.Printf("文件或文件夹 %s 不存在\n", path)
	} else {
    
    
		fmt.Printf("获取文件或文件夹 %s 信息时发生错误:%v\n", path, err)
	}
}

os delete file or folder

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	var err error
	// 删除指定的文件夹或文件(文件夹必须为空)
	err = os.Remove("example/a/b")
	if err != nil {
    
    
		fmt.Println(err) // remove example/a/b: directory not empty
	} else {
    
    
		fmt.Println("Success!")
	}
}
package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	var err error
	// 删除指定的文件夹及其所有子文件夹和文件
	err = os.RemoveAll("example/a/b")
	if err != nil {
    
    
		fmt.Println(err)
	} else {
    
    
		fmt.Println("Success!")
	}
}

os file folder rename

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	err := os.Rename("example/a", "example/b") //err := os.Rename("test.txt", "text.log")
	if err != nil {
    
    
		fmt.Println(err) // remove example/a/b: directory not empty
	} else {
    
    
		fmt.Println("Success!")
	}
}

os environment variable

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	// 获取所有的环境变量
	envs := os.Environ()
	for i, env := range envs {
    
    
		fmt.Println(i+1, env)
	}

	// 获取指定环境变量key的值
	home := os.Getenv("HOME")
	fmt.Println(home)

	// 获取指定环境变量key的值和是否存在的状态
	shell, isExist := os.LookupEnv("SHELL")
	fmt.Println(shell, isExist)

	//os.Setenv(key, value string) error:设置指定环境变量key的值为value。
	//os.Unsetenv(key string) error:删除指定环境变量key。
	//os.Clearenv():清空所有的环境变量。
	//os.ExpandEnv(s string) string:将字符串s中的${var}或$var替换为相应的环境变量的值。
}

io

io.Copy

package main

import (
	"io"
	"os"
)

func main() {
    
    
	i, _ := os.Open("input.txt")
	defer i.Close()
	o, _ := os.Create("output.txt")
	defer o.Close()
	io.Copy(o, i)
}

ioutil

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
    
    
	text, _ := ioutil.ReadFile("input.txt")
	fmt.Printf("%s", text)
}

bufio

Used to provide buffered I/O operations. It can improve performance and reduce the number of system calls when reading and writing files, network connections, and other I/O operations

log

Record some information when the program is running, such as error information, warning information, debugging information, etc.

json

Data conversion to JSON formatted data

package main

import (
	"encoding/json"
	"fmt"
)

type UserInfo struct {
    
    
	Name   string  `json:"name"`
	Age    int     `json:"age"`
	Height float64 `json:"height"`
	List   []any   `json:"list"`
}

func main() {
    
    
	userInfo := UserInfo{
    
    Name: "Lee", Age: 18, Height: 171.123, List: []any{
    
    1, "Hello", false}}
	jsonBytes, err := json.Marshal(userInfo)
	if err != nil {
    
    
		fmt.Println(err)
		return
	}
	fmt.Println(string(jsonBytes)) // {"name":"Lee","age":18,"height":171.123,"list":[1,"Hello",false]}
}

parsing json

package main

import (
	"encoding/json"
	"fmt"
)

type UserInfo struct {
    
    
	Name   string  `json:"name"`
	Age    int     `json:"age"`
	Height float64 `json:"height"`
	List   []any   `json:"list"`
}

func main() {
    
    
	jsonStr := `{"name":"Lee","age":18,"height":171.123,"list":[1,"Hello",false]}`

	var userInfo UserInfo
	err := json.Unmarshal([]byte(jsonStr), &userInfo)
	if err != nil {
    
    
		fmt.Println(err)
		return
	}
	fmt.Println(userInfo) // {Lee 18 171.123 [1 Hello false]}
}

xml

Data conversion to data in xml format

package main

import (
	"encoding/xml"
	"fmt"
)

type UserInfo struct {
    
    
	Name   string  `xml:"name"`
	Age    int     `xml:"age"`
	Height float64 `xml:"height"`
	List   []any   `xml:"list>item"`
}

func main() {
    
    
	userInfo := UserInfo{
    
    Name: "Lee", Age: 18, Height: 171.123, List: []any{
    
    1, "Hello", false}}
	xmlBytes, err := xml.Marshal(userInfo)
	if err != nil {
    
    
		fmt.Println(err)
		return
	}
	fmt.Println(string(xmlBytes)) // <UserInfo><name>Lee</name><age>18</age><height>171.123</height><list><item>1</item><item>Hello</item><item>false</item></list></UserInfo>
}

parsing xml

must be modified anyto stringtype

package main

import (
	"encoding/xml"
	"fmt"
)

type UserInfo struct {
    
    
	Name   string  `xml:"name"`
	Age    int     `xml:"age"`
	Height float64 `xml:"height"`
	List   []any   `xml:"list>item"`
}

type Info struct {
    
    
	UserInfo
	List []string `xml:"list>item"`
}

func main() {
    
    
	xmlStr := `<UserInfo><name>Lee</name><age>18</age><height>171.123</height><list><item>1</item><item>Hello</item><item>false</item></list></UserInfo>`
	var userInfo Info
	err := xml.Unmarshal([]byte(xmlStr), &userInfo)
	if err != nil {
    
    
		fmt.Println(err)
		return
	}
	fmt.Println(userInfo) // {
    
    {Lee 18 171.123 []} [1 Hello false]}
}

Guess you like

Origin blog.csdn.net/weixin_43526371/article/details/130470302