Golang Write formated strings to file

huangapple go评论93阅读模式
英文:

Golang Write formated strings to file

问题

我正在尝试打开一个包含以下内容的文件:

MOT021L3
MLK407L3
MLK485L3
  • 我正在读取文件并创建一个切片。我想要遍历这个切片并删除“L3”,只保留MOT021。

我能够成功地将输出打印到终端,但我不知道如何将数据添加到具有相同格式的文件中。写入文件的输出是:

MOT021L3MLK407L3MLK485L3

我在新文件中期望的结果是:

MOT021
MLK407
MLK485

代码:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
	//读取文件
	n, err := ioutil.ReadFile("box_1")
	if err != nil {
		fmt.Println(err)
	}
	a := string(n)

	sliceData := strings.Split(string(a), "\n")

	f, err := os.Create("box_2")
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()

	//var trimmedSlice string
	for _, i := range sliceData {
		trimmedSlice := (strings.TrimSuffix(i, "L3"))
		fmt.Println(trimmedSlice)
		f.Write([]byte(trimmedSlice))
	}
	f.Close()

}
英文:

I'm trying to open a file that has the content:

MOT021L3
MLK407L3
MLK485L3
  • I'm reading the file & creating a slice. From that slice, I want to iterate through it and remove "L3". Keeping MOT021.

I'm able to successfully print the output to the terminal but I am not sure how to add the data to a file with the same format. The output that is being written to the file is:

MOT021L3MLK407L3MLK485L3

The result I'm looking for in the new file is.

MOT021
MLK407
MLK485

Code:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
	//Read File
	n, err := ioutil.ReadFile("box_1")
	if err != nil {
		fmt.Println(err)
	}
	a := string(n)

	sliceData := strings.Split(string(a), "\n")

	f, err := os.Create("box_2")
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()

	//var trimmedSlice string
	for _, i := range sliceData {
		trimmedSlice := (strings.TrimSuffix(i, "L3"))
		fmt.Println(trimmedSlice)
		f.Write([]byte(trimmedSlice))
	}
	f.Close()

}

答案1

得分: 0

这似乎可以实现:

package main

import (
   "bufio"
   "os"
)

func main() {
   in, e := os.Open("in.txt")
   if e != nil {
      panic(e)
   }
   defer in.Close()
   out, e := os.Create("out.txt")
   if e != nil {
      panic(e)
   }
   defer out.Close()
   s := bufio.NewScanner(in)
   for s.Scan() {
      out.WriteString(s.Text()[:6] + "\n")
   }
}

https://golang.org/pkg/os#File.WriteString

英文:

This seems to do it:

package main

import (
   "bufio"
   "os"
)

func main() {
   in, e := os.Open("in.txt")
   if e != nil {
      panic(e)
   }
   defer in.Close()
   out, e := os.Create("out.txt")
   if e != nil {
      panic(e)
   }
   defer out.Close()
   s := bufio.NewScanner(in)
   for s.Scan() {
      out.WriteString(s.Text()[:6] + "\n")
   }
}

https://golang.org/pkg/os#File.WriteString

huangapple
  • 本文由 发表于 2021年6月7日 08:33:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/67864746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定