Files

The basics of reading and writing files are shown in the example below. This example opens the file for reading, reads the entire file as a String, and then closes the file. It then reopens it for writing, writes the modified contents back to the file and closes it again.


                f = open("hello1.txt", "r")
                contents = read(f, String)
                s = uppercase(contents)
                close(f)
                
                f = open("hello1.txt", "w")
                write(f, s)
                close(f)
            

We can use the do syntax, the file is closed at the end of the block. But the contents of the file read in by the read function is private to the do block. So assign the output of the block to something so that it can be used subsequently.


                data = open("infile.txt") do f
                    read(f, String)
                end
                
                # Code to write the data to a new file
                open("outfile.txt", "w") do f
                    write(f, data)
                end
             

The above code could be replaced by the built in function cp. However, beware that the help for this function means exactly what it says:

cp(src::AbstractString, dst::AbstractString; force::Bool=false, follow_symlinks::Bool=false)
Copy the file, link, or directory from src to dst.
force=true will first remove an existing dst.
The cp function is different from the cp command.
The cp function always operates on the assumption that dst is a file,
while the command does different things depending on whether dst is a directory or a file.

Using force=true when dst is a directory will result in loss of all the contents present in the dst directory, and dst will become a file that has the contents of src instead.

So the point of the example code is that some other processing happens in one or both of the blocks!

A final note: the do block idea can be used to add an anonymous function to a call that is expecting a function. e.g. map:


                a = 1:10
                map(a) do n
                   n*2
                end
            

This code prints out the even numbers from 2 to 20. It is equivalent to [2n for n in 1:10]