go语言用字符串替代txt文件第四行的内容
时间: 2023-12-02 10:02:37 浏览: 30
以下是用 Go 语言替换文本文件第四行内容的示例代码:
```go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// 打开文件
file, err := os.OpenFile("textfile.txt", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
defer file.Close()
// 读取文件内容
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// 替换第四行内容
if len(lines) >= 4 {
lines[3] = "New content"
}
// 将修改后的内容写回文件
file.Seek(0, 0)
file.Truncate(0)
writer := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(writer, line)
}
writer.Flush()
}
```
在上面的示例代码中,我们使用 `os.OpenFile` 函数打开文本文件并读取其中的内容。然后,我们使用 `bufio.NewScanner` 函数逐行读取文件内容并将每一行存储在一个字符串切片中。接下来,我们检查这个字符串切片是否有至少 4 行,如果有,就将第四行替换为新的内容。最后,我们使用 `os.File` 的 `Seek` 和 `Truncate` 方法清空文件内容,并使用 `bufio.NewWriter` 函数将修改后的内容写回文件中。