File Handling in Julia - GeeksforGeeks

10 Jul, 2020
Julia is a high-level, high-performance, and dynamic programming language that supports file Handling i.e., to read and write files. It is much easier for Julia to open, read, and write files as compared to various other languages. It has a similar way to handle the file as compared to python. It provides a combination of languages such as C (for its powerful performance) and Python(for its simplicity). As I/O streams are mostly used for data science and statistical analysis Julia provides all features for data science. It is excellent in numerical computing and support for parallel programming is also provided. Julia provides some measure of manual control over garbage collection and it doesn’t burden the user with the details of allocating and freeing memory.
In order to create a file, we first use pwd() function to know the current working directory. If you want to change the working directory use cd(path) and provide the path where you want to create the file.
Once the directory is set we use touch(filename) function in order to create a new file. In this example, we are creating a .txt file. 
# Creating a file using touch() functiontouch("geek.txt")
Once the file is created we use the open(filename, mode) function in Julia to open the file. The open(filename, mode) takes two arguments one is the filename and other is the mode. Since we are just reading the file we would only require “r” (read) mode to open the file. The open() function returns a file object.
It has various other modes like “w” for writing etc. for various other purposes.
# The file "geek.txt" will be opened and # open() will return a file object stored in f.f = open("geek.txt", "r")
There exists another invocation of open() function where we can avoid defining a function with the help of do syntax. This syntax helps us to remove the ambiguity of closing the file after modifying the contents of the file. The do block also helps to easily write the code for modify the file. Also, it is very easy to implement.
# opening the file wrapped in do blockopen("geek.txt") do file    # do something with fileend
In order to read the context of the file, we use read() function to read the entire content of the file.
# The context of the file will be stored# in the data variable as Stringdata = read(f, String)
There are various functions that help in reading the context according to our convenience.
We can use eachline(filename) function which is used as an iterator that allows you to process file each line at a time.
# The eachline() function will print# the context line by lineopen("geek.txt") do file    for li in eachline(file)        println("$(li)")    endend
We can also use readlines() to read in the whole file as an array, with each line an element:
# The readline() function to print the context as an arrayf = open("geeks.txt", "r")lines = readlines(f)
We can use the DelimitedFiles.readdlm() function to read lines delimited with certain characters, such as arrays stored as text files, data files, and tables. The format readdlm(source; options...) .The end of line delimiter is taken as \n. Now if all the data is numeric in nature, the result will be a numeric array and if some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.
For example: In this example we are taking two array x[] array is a int array where as y[] is a char array. After writing content we used readlm() function.
# importing DelimitedFilesusing DelimitedFiles  # x arrayx = [4; 3; 2; 1];  #y -arrayy = ["a"; "b"; "c"; "d"];  #Writing contents to the fileopen("geek.txt", "w") do io     writedlm(io, [x y])end;  #readlm() method to read the DelimitedFilesreaddlm("geek.txt")
In order to write in a file, we need to open the file in write mode by passing “w” as a parameter. Now to write to a file in Julia we use write(fileobject, string) method. It takes two arguments, first is the file object and the second is the String provided.
The most important step is to close the file If you don’t close the file the contents of the file would be empty. This is because the IOStream must be closed before the write is actually flushed to disk.
# Opening file in write modef = open("geek.txt", "w")  # writing to a file using write() methodwrite(f, " Hello World")  # We need to close the file in order to write the content from the disk to fileclose(f)
Sometimes it becomes tedious to remember to open and close the file and it very common pattern to open a File modify its content and closing it again. So In order to remove this ambiguity, there exists another invocation of open which takes a function as its first argument and filename as its second. It is very helpful as it opens the file, calls the function with the file as an argument, and then closes it again.
For example: If you want to make all letters UPPERCASE in the file we can define a function like this:
# function to make contents of File in Uppercasefunction make_upper(f::IOStream)    return uppercase(read(f, String))end  # Now to call the functionopen(make_upper, "geek.txt")
There exists another invocation of open function where we can avoid defining a function with the help of do syntax.
# Implementation of do syntax # in order to avoid writing a function.open("geek.txt") do f       uppercase(read(f, String))end
We also use DelimitedFiles.writedlm() function to write to a file. The general parameters of the function is given by writedlm(f, A, delim=’\t’; opts). 
Here A (a vector, matrix, or an iterable collection of iterable rows) as text to f (either a filename string or an IO stream) using the given delimiter delim (which defaults to tab, but can be any printable Julia object, typically a Char or AbstractString).
Below is the following implementation:
# importing DelimitedFIlesusing DelimitedFiles  # x arrayx = [4; 3; 2; 1];  # y arrayy = ["a"; "b"; "c"; "d"];  # writedlm)() methodopen("geek.txt", "w") do io     writedlm(io, [x y])end;
In order to close the file in Julia, we can simply use close(fileobject) function. It takes the file object as an argument and just close the connection.
# The close() function to close the fileclose(f)
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Manipulating matrices in Julia
Comments in Julia
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Tuples in Julia
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method