How keep adding data to text file not rewrite him?


(Mantas Silanskas) #1
nf, err := os.Create("results.txt")
		if err != nil {
			panic(err)
		}
		defer func() {
			err := nf.Close()
			if err != nil {
				panic(err)
			}
		}()

		timeOfUpdate := time.Now()
		_, err = fmt.Fprintf(nf, "File last time updated -  %v\n", timeOfUpdate.Format("2006.01.02 15:04:05"))
		if err != nil {
			panic(err)
		}
		length := len(results)
		_, err = fmt.Fprintf(nf, "Reisai without GPS -  %v\n", length)
		if err != nil {
			panic(err)
		}
		for key, value := range results {
			_, err := fmt.Fprintf(nf, "Bus number: %v\n Full bus info: %v\n", key, value)
			if err != nil {
				panic(err)
			}
			nf.Sync()
		}

I am using code like this to print data to file and I want to keep adding data to file not rewrite him every time.

I think my problem is that every time I launch this KingPing case I create file

nf, err := os.Create("results.txt")
		if err != nil {
			panic(err)
		}
		defer func() {
			err := nf.Close()
			if err != nil {
				panic(err)
			}
		}()

My full KingPin case :

case results.FullCommand():

		rp := reisai.NewReisaiParser(&reisai.ReisaiParserOpts{MinutesSinceMidnight: mins.GetMinutesSinceMidnight()})
		reisai1, err := rp.ParseDefaultReisai()
		if err != nil {
			panic(err)
		}

		ep := gps.NewGpsParser(&gps.GpsParserOpts{})
		gps1, err := ep.ParseDefaultGps()
		if err != nil {
			panic(err)
		}

		analysis.Analyze(gps1, reisai1)

		results := make(map[string]*reisai.ReisaiDataRow)
		for NewMap, reisai := range reisai1 {
			results[NewMap] = reisai
		}
		nf, err := os.Create("results.txt")
		if err != nil {
			panic(err)
		}
		defer func() {
			err := nf.Close()
			if err != nil {
				panic(err)
			}
		}()

		timeOfUpdate := time.Now()
		_, err = fmt.Fprintf(nf, "File last time updated -  %v\n", timeOfUpdate.Format("2006.01.02 15:04:05"))
		if err != nil {
			panic(err)
		}
		length := len(results)
		_, err = fmt.Fprintf(nf, "Reisai without GPS -  %v\n", length)
		if err != nil {
			panic(err)
		}
		for key, value := range results {
			_, err := fmt.Fprintf(nf, "Bus number: %v\n Full bus info: %v\n", key, value)
			if err != nil {
				panic(err)
			}
			nf.Sync()
		}

		fmt.Println("List of not working GPS systems has been updated and saved into file results.txt")
	}

(Cory Galyna) #2

Open with append or create permission. Example:

f, err := os.OpenFile("file.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)

(Mantas Silanskas) #3

Thank you, Cory