从Golang的文本文件中读取?

时间:2016-07-31 14:11:20

标签: go

我想这样做:

  1. 从文本文件中读取一行。
  2. 处理这条线。
  3. 删除该行。
  4. 我的第一个想法是用ioutil.Readfile(),将整个文件读入内存 但我不确定如何在处理完行后更新文本文件,
    如果在将文本文件读入内存后将额外的行添加到文本文件中会发生什么?

    我通常会编写shell脚本,并会执行以下操作:

    while read -r line; do
        echo "${line}"
        sed -i 1d "${myList}"
    done < "${myList}"
    

    在Golang中执行此操作的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

使用fout包。

以下是打开文本文件并循环遍历每个bufio的基本语法。

line

答案 1 :(得分:0)

你有一些选择:
1-读取文件,处理它,然后将其写回(你需要锁定该文件) 2-使用二进制文件并发明(利用)特殊数据结构(如链表)来优化文本处理(带线锁)。
3- 使用现成的数据库 4-在文件中使用虚拟文件系统,并将每行视为一个文件,请参阅:https://github.com/lotrfan/vfshttps://github.com/blang/vfs

使用文件管理器(如数据库服务器)解决了文件锁定困境。

如果使用文件的目的是单向通信,发送者程序只是添加新行,接收器程序只是删除它,最好使用os管道(命名管道(FIFO))或其他interop方法

参见Linux:Unix FIFO in go?
对于Windows:https://github.com/natefinch/npipe

示例文件编写器:

DELETE FROM table
WHERE column IN ('".
    implode($array, "'separator'") // separator = ', ' for arrays. Be careful for space after the comma.
."')
AND ...

示例文件阅读器:

package main

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

func main() {
    f, err := os.OpenFile("/tmp/file.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    for i := 0; ; i++ {
        w := bufio.NewWriter(f)
        _, err := fmt.Fprintln(w, i)
        if err != nil {
            panic(err)
        }
        w.Flush() // Flush writes any buffered data to the underlying io.Writer.
        f.Sync()  // commit the current contents of the file to stable storage.
        fmt.Println("write", i)
        time.Sleep(500 * time.Millisecond)
    }
}
相关问题