Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we use julia to read through each character of a .txt file, one at a time?

I am trying to go through a .txt file with Julia, and I need to be able to look at every character as the program reads through the file. What little I have found on the Julia Docs page is how to read line by line. I know that the basic set up should be something like this

file = open("testfile.txt","r");
while !eof(file)
    //look at each character and store it to a variable 

Once it is stored into a variable I know how to manipulate it, but I can't figure out how to get it into the variable storage.

like image 279
Noah Franck Avatar asked Sep 11 '18 17:09

Noah Franck


People also ask

How do I open a TXT file in Julia?

Opening a File txt” placed in the same working directory along with Julia's implementation file. Open a file using open() and assign it to a variable which is the instance of the opened file, then make use of that variable for further operations to be performed on the opened file. Then close the file using close().

How to write to a file in Julia?

We can write in an existing file in Julia by using the write(fileobject, string) method. To write in a file, we need to open the file in write mode. To do so, we have to pass "w" in the mode argument. The most important step while writing a file is to close the file after the computation.


1 Answers

Use read function like this:

file = open("testfile.txt","r")
while !eof(file)
    c = read(file, Char)
    # your stuff
end
close(file)

This will read it character by character using UTF-8.

If you want to read it byte by byte then use:

file = open("testfile.txt","r")
while !eof(file)
    i = read(file, UInt8)
    # your stuff
end
close(file)

Note that you can use do block to automatically close a file when you leave it:

open("testfile.txt","r") do file
    while !eof(file)
        i = read(file, UInt8)
        # your stuff
    end
end

For a more complete example you might want to have look e.g. at this function https://github.com/bkamins/Nanocsv.jl/blob/master/src/csvreader.jl#L1 that uses pattern read(io, Char) to parse CSV files.

like image 157
Bogumił Kamiński Avatar answered Jan 26 '23 06:01

Bogumił Kamiński