Deleting content of file without deleting the file in Golang


I have a CSV file let’s say crop.csv
I want to delete its content only (which will make crop.csv empty) without deleting the crop.csv file.


Use the os.Truncate() function which truncates a file. Specify 0 for the new size, so it’ll be empty:

if err := os.Truncate("/path/to/your/file/crop.csv", 0); err != nil {
    log.Printf("Failed to truncate: %v", err)

Note that as a result, your file will be empty, but truncation does not take care of making the data unrecoverable. So if someone gets access to your hard drive, it may be possible to recover the contents.

Answered By – icza

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.