栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将文本文件读入字符串数组(并写入)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将文本文件读入字符串数组(并写入)

从Go1.1版本开始,有一个bufio.Scanner
API可以轻松读取文件中的行。考虑上面的以下示例,该示例使用Scanner重写:

package mainimport (    "bufio"    "fmt"    "log"    "os")// readLines reads a whole file into memory// and returns a slice of its lines.func readLines(path string) ([]string, error) {    file, err := os.Open(path)    if err != nil {        return nil, err    }    defer file.Close()    var lines []string    scanner := bufio.NewScanner(file)    for scanner.Scan() {        lines = append(lines, scanner.Text())    }    return lines, scanner.Err()}// writeLines writes the lines to the given file.func writeLines(lines []string, path string) error {    file, err := os.Create(path)    if err != nil {        return err    }    defer file.Close()    w := bufio.NewWriter(file)    for _, line := range lines {        fmt.Fprintln(w, line)    }    return w.Flush()}func main() {    lines, err := readLines("foo.in.txt")    if err != nil {        log.Fatalf("readLines: %s", err)    }    for i, line := range lines {        fmt.Println(i, line)    }    if err := writeLines(lines, "foo.out.txt"); err != nil {        log.Fatalf("writeLines: %s", err)    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号