File Handling in Julia

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.

Creating a File

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.
currentdirectory

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. 

filter_none

edit
close

play_arrow

link
brightness_4
code

# Creating a file using touch() function
touch("geek.txt")

chevron_right


contentsoffile

Opening a File in Julia

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# The file "geek.txt" will be opened and 
# open() will return a file object stored in f.
f = open("geek.txt", "r")

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# opening the file wrapped in do block
open("geek.txt") do file
    # do something with file
end

chevron_right


Reading a File In Julia

In order to read the context of the file, we use read() function to read the entire content of the file.

filter_none

edit
close

play_arrow

link
brightness_4
code

# The context of the file will be stored
# in the data variable as String
data = read(f, String)

chevron_right


readfunction

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# The eachline() function will print
# the context line by line
open("geek.txt") do file
    for li in eachline(file)
        println("$(li)")
    end
end

chevron_right


eachlinefunction

We can also use readlines() to read in the whole file as an array, with each line an element:



filter_none

edit
close

play_arrow

link
brightness_4
code

# The readline() function to print the context as an array
f = open("geeks.txt", "r")
lines = readlines(f)

chevron_right


readlinesfunction

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing DelimitedFiles
using DelimitedFiles
  
# x array
x = [4; 3; 2; 1];
  
#y -array
y = ["a"; "b"; "c"; "d"];
  
#Writing contents to the file
open("geek.txt", "w") do io
     writedlm(io, [x y])
end;
  
#readlm() method to read the DelimitedFiles
readdlm("geek.txt")

chevron_right


readlmfunction

Writing To a File In Julia

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Opening file in write mode
f = open("geek.txt", "w")
  
# writing to a file using write() method
write(f, " Hello World")
  
# We need to close the file in order to write the content from the disk to file
close(f)

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to make contents of File in Uppercase
function make_upper(f::IOStream)
    return uppercase(read(f, String))
end
  
# Now to call the function
open(make_upper, "geek.txt")

chevron_right


uppercasefunction

There exists another invocation of open function where we can avoid defining a function with the help of do syntax.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Implementation of do syntax 
# in order to avoid writing a function.
open("geek.txt") do f
       uppercase(read(f, String))
end

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing DelimitedFIles
using DelimitedFiles
  
# x array
x = [4; 3; 2; 1];
  
# y array
y = ["a"; "b"; "c"; "d"];
  
# writedlm)() method
open("geek.txt", "w") do io
     writedlm(io, [x y])
end;

chevron_right


Closing a File In Julia

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# The close() function to close the file
close(f)

chevron_right


closefile




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.