3 回答

TA贡献1818条经验 获得超3个赞
这是一个老问题,但如果有人正在寻找解决方案,我编写了一个包来处理文件中的任何行。链接在这里。它可以打开一个文件并搜索到任何行位置,而无需将整个文件读入内存并进行拆分。
import "github.com/stoicperlman/fls"
// This is just a wrapper around os.OpenFile. Alternatively
// you could open from os.File and use fls.LineFile(file) to get f
f, err := fls.OpenFile("test.log", os.O_CREATE|os.O_WRONLY, 0600)
defer f.Close()
// return begining line 1/begining of file
// equivalent to f.Seek(0, io.SeekStart)
pos, err := f.SeekLine(0, io.SeekStart)
// return begining line 2
pos, err := f.SeekLine(1, io.SeekStart)
// return begining of last line
pos, err := f.SeekLine(0, io.SeekEnd)
// return begining of second to last line
pos, err := f.SeekLine(-1, io.SeekEnd)
不幸的是,我不确定您将如何删除,这只是让您到达文件中的正确位置。对于您的情况,您可以使用它转到要删除的行并保存位置。然后寻找下一行并保存。您现在有要删除的行的书挡。
// might want lineToDelete - 1
// this acts like 0 based array
pos1, err := f.SeekLine(lineToDelete, io.SeekStart)
// skip ahead 1 line
pos2, err := f.SeekLine(1, io.SeekCurrent)
// pos2 will be the position of the first character in next line
// might want pos2 - 1 depending on how the function works
DeleteBytesFromFileFunction(f, pos1, pos2)

TA贡献1846条经验 获得超7个赞
根据我对 linecache 模块的读取,它需要一个文件并将其分解为基于 '\n' 行结尾的数组。您可以使用strings或bytes复制 Go 中的相同行为。您还可以使用bufio库逐行读取文件,并仅存储或保存所需的行。
package main
import (
"bytes"
"fmt"
)
import "io/ioutil"
func main() {
b, e := ioutil.ReadFile("filename.txt")
if e != nil {
panic(e)
}
array := bytes.Split(b, []byte("\n"))
fmt.Printf("%v", array)
}

TA贡献1895条经验 获得超7个赞
我编写了一个小函数,允许您从文件中删除特定行。
package main
import (
"io/ioutil"
"os"
"strings"
)
func main() {
path := "path/to/file.txt"
removeLine(path, 2)
}
func removeLine(path string, lineNumber int) {
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
info, _ := os.Stat(path)
mode := info.Mode()
array := strings.Split(string(file), "\n")
array = append(array[:lineNumber], array[lineNumber+1:]...)
ioutil.WriteFile(path, []byte(strings.Join(array, "\n")), mode)
}
- 3 回答
- 0 关注
- 342 浏览
添加回答
举报