Top

Golang之文件与文件夹操作大汇总


本文属于原创,转载注明出处,欢迎关注微信小程序小白AI或者网站 https://xiaobaiai.net

相关包

package note
io io包为I/O操作提供了基础的抽象接口
os os包中实现了平台无关的功能函数;操作失败,返回的不仅仅是简单的错误码,而是更多的错误信息提示
ioutil 提供了文件和目录读取基本操作函数,临时目录和文件操作函数
bufio bufio包实现了缓存IO,封装了io.Reader和io.Write对象,实现了io.Reader和io.Write接口

pkg io

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
......
func ReadFull(r Reader, buf []byte) (n int, err error)
func WriteString(w Writer, s string) (n int, err error)
type ByteReader interface{ ... }
type ByteScanner interface{ ... }
type ByteWriter interface{ ... }
type Closer interface{ ... }
type LimitedReader struct{ ... }
type PipeReader struct{ ... }
type PipeWriter struct{ ... }
type ReadCloser interface{ ... }
type ReadSeeker interface{ ... }
type ReadWriteCloser interface{ ... }
type ReadWriteSeeker interface{ ... }
type ReadWriter interface{ ... }
type Reader interface{ ... }
func LimitReader(r Reader, n int64) Reader
func MultiReader(readers ...Reader) Reader
func TeeReader(r Reader, w Writer) Reader
type ReaderAt interface{ ... }
type ReaderFrom interface{ ... }
type RuneReader interface{ ... }
type RuneScanner interface{ ... }
......

pkg os

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
......
func Chdir(dir string) error
func Chmod(name string, mode FileMode) error
func Chown(name string, uid, gid int) error
func Chtimes(name string, atime time.Time, mtime time.Time) error
func Clearenv()
func Environ() []string
func Executable() (string, error)
func Exit(code int)
func Expand(s string, mapping func(string) string) string
func ExpandEnv(s string) string
func Getegid() int
func Getenv(key string) string
func Geteuid() int
func Getgid() int
func Getgroups() ([]int, error)
func Getpagesize() int
func Getpid() int
func Getppid() int
func Getuid() int
func Getwd() (dir string, err error)
func Hostname() (name string, err error)
func IsExist(err error) bool
func IsNotExist(err error) bool
func IsPathSeparator(c uint8) bool
func IsPermission(err error) bool
func IsTimeout(err error) bool
func Lchown(name string, uid, gid int) error
func Link(oldname, newname string) error
func LookupEnv(key string) (string, bool)
func Mkdir(name string, perm FileMode) error
func MkdirAll(path string, perm FileMode) error
func NewSyscallError(syscall string, err error) error
func Pipe() (r *File, w *File, err error)
func Readlink(name string) (string, error)
func Remove(name string) error
func RemoveAll(path string) error
func Rename(oldpath, newpath string) error
func SameFile(fi1, fi2 FileInfo) bool
func Setenv(key, value string) error
func Symlink(oldname, newname string) error
func TempDir() string
func Truncate(name string, size int64) error
func Unsetenv(key string) error
func UserCacheDir() (string, error)
func UserHomeDir() (string, error)
...

pkg io/ioutil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
......
var Discard io.Writer = devNull(0)
func NopCloser(r io.Reader) io.ReadCloser
func ReadAll(r io.Reader) ([]byte, error)
func ReadDir(dirname string) ([]os.FileInfo, error)
func ReadFile(filename string) ([]byte, error)
func TempDir(dir, prefix string) (name string, err error)
func TempFile(dir, pattern string) (f *os.File, err error)
func WriteFile(filename string, data []byte, perm os.FileMode) error
......

type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes for regular files; system-dependent for others
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // abbreviation for Mode().IsDir()
Sys() interface{} // underlying data source (can return nil)
}
......

pkg bufio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
......
const MaxScanTokenSize = 64 * 1024 ...
var ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") ...
var ErrTooLong = errors.New("bufio.Scanner: token too long") ...
var ErrFinalToken = errors.New("final token")
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
type ReadWriter struct{ ... }
func NewReadWriter(r *Reader, w *Writer) *ReadWriter
type Reader struct{ ... }
func NewReader(rd io.Reader) *Reader
func NewReaderSize(rd io.Reader, size int) *Reader
type Scanner struct{ ... }
func NewScanner(r io.Reader) *Scanner
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)
type Writer struct{ ... }
func NewWriter(w io.Writer) *Writer
func NewWriterSize(w io.Writer, size int) *Writer
......

获取文件夹下内容

通过io/ioutilpackage下的ReadDir函数直接获取指定文件夹下的文件和文件夹列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package blog

import (
"fmt"
"io/ioutil"
"testing"
)

func TestOperation(t *testing.T) {
files, err := ioutil.ReadDir("../generator")
if err != nil {
panic("failed to read directory")
}
for _, f := range files {
if f.IsDir() {
fmt.Println("dir: ", f.Name())
} else {
fmt.Println("file: ", f.Name())
}

}
}

按行读取文本文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func GetLine(textfile string) error {
file, err := os.Open(textfile)
if err != nil {
log.Printf("Cannot open text file: %s, err: [%v]", textfile, err)
return err
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text() // or
//line := scanner.Bytes()

//do_your_function(line)
fmt.Printf("%s\n", line)
}

if err := scanner.Err(); err != nil {
log.Printf("Cannot scanner text file: %s, err: [%v]", textfile, err)
return err
}

return nil
}

按行写文本文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 写map[string]string到文件
func WriteMaptoFile(m map[string]string, filePath string) error {
f, err := os.Create(filePath)
if err != nil {
fmt.Printf("create map file error: %v\n", err)
return err
}
defer f.Close()

w := bufio.NewWriter(f)
for k, v := range m {
lineStr := fmt.Sprintf("%s^%s", k, v)
fmt.Fprintln(w, lineStr)
}
return w.Flush()
}

[]byte直接写文件

1
2
3
// 比如在使用json序列化后得到[]byte,直接写入文件
// 指定文件路径和文件名 + 数据 + 文件权限
err := ioutil.WriteFile("/home/ethan/go/output.json", data, 0644)

持续汇总更新…



授权:知识共享署名-相同方式共享 4.0 国际许可协议
网站信息: 小白AI.易名
文章标题:Golang之文件与文件夹操作大汇总
永久链接:https://xiaobaiai.net/2019/20190807125016.html
关注公众号:小白AI
关注微信小程序:小白AI博客
微信打赏 支付宝打赏