Basic writing to file question(s)

Hello! I’m still pretty new. I’ve checked the documentation on this but am not getting the full picture yet.

Here’s my situation: I’m doing some benchmarking and want to test my program on different inputs one at a time. Each time I run the program, I want to save some information to a markdown file. Then I want to change the inputs, run the program again, and append the new information to the same markdown file.

I know that to make a file I use the command touch. Question: I am in a working directory, .atom and have been unable to change this working directory by using cd in the the REPL. Can I have touch() make a file in a different directory? For example, I have a subdirectory in .atom where I am working on this project and I would like to save it here.

Next, I am also having problems appending my file. I created a file in the REPL and am opening it in append mode in my program using open(). I am able to write successfully to the file using write. However, when I run the program again, it overwrites my file. Based on the documentation, it seems like I should be using write!() which is in the LibGit2 library, but the function isn’t recognized when I call it. LibGit2 is installed in my home directory so it should be working. Will write!() work as I think it will and is it depricated? How should I append the file otherwise?

Thanks for your time!

You should really post a minimal, running example illustrating your point. You know, a few lines of code say more than a thousand words.

https://discourse.julialang.org/t/please-read-make-it-easier-to-help-you

open(“comparison”,“a”)
write(“comparison.md”, "# " , gallery, string(x0), " to ", string(x1), " degree ", string(n))
close

Well, hardly a MWE… please do read the link I sent. But try something like

  julia> io = open("myfile.txt", "a");                                                                                                                                                          
                                                                                                                                                                                                
  julia> write(io, "Hello world!");                                                                                                                                                             
                                                                                                                                                                                                
  julia> close(io); 

(from the doc-string) Note the io. In your example you open a file with open and then open another one with write.

3 Likes

very helpful and appreciated!

1 Like

To help you not forget/fail to close the stream, you can use

open(filename, "a") do io
    write(io, contents)
end
1 Like