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

Viewed 921

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.

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.

Related