Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to a file if it exists else create a new and write to it [duplicate]

Tags:

go

I have a file that I would like to add some contents to. I first check if that file exists. If it does, I add contents to it. If not, I just create a new file with that name and write to it. For this, I am doing something like:

if _, err := os.Stat(filename); os.IsNotExist(err) {
    f, err := os.Create(filename)
    if err != nil {
        panic(err)
    }
        ....
} else {
    f, _ := os.OpenFile(filename, os.O_RDWR|os.O_APPEND, 0660);
    ....
}

Is it possible to make this code shorter like 1-2 liner?

like image 313
user1892775 Avatar asked Dec 12 '18 18:12

user1892775


People also ask

Does append create a new file?

Append mode adds information to an existing file, placing the pointer at the end. If a file does not exist, append mode creates the file.

Which mode to append additional data to the data already in an existing file?

The "a" mode allows you to open a file to append some content to it. And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.

How do you append one file to another file using python write code for the same statement?

Print the contents of the files before appending using the read() function. Close both the files using the close() function. Open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function.

How do you write to a file in append mode?

Open file in append mode and write to itOpen the file in append 'a' mode, and write to it using write() method. Inside write() method, a string "new text" is passed. This text is seen on the file as shown above.


1 Answers

The OpenFile example shows how to append to existing file or create a new file. The code is:

// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Fatal(err)
}
like image 131
Bayta Darell Avatar answered Oct 25 '22 23:10

Bayta Darell