9

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.

rickhg12hs
  • 10,638
  • 6
  • 24
  • 42
Noah Franck
  • 127
  • 1
  • 1
  • 7

1 Answers1

13

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.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • Thanks for the help. This was what I needed. I saw this in the help, but didn't realize that char had to be written as **Char** to be correctly passed. – Noah Franck Sep 14 '18 at 20:26
  • @NoahFranck The above answer looks great. Why not accept it so the person who took the time to write it gets the credit that acceptance gives? – Julia Learner Sep 26 '18 at 00:09
  • @JuliaLearner I honestly didn't know that there was an option to select an answer or mark that it was most beneficial until you mentioned it. – Noah Franck Sep 28 '18 at 19:58
  • @NoahFranck Thanks for noticing. I noticed another one as well [here](https://stackoverflow.com/questions/52339092/julia-passing-arguments-reading-the-command-line/52437448#52437448) you might consider checking. – Julia Learner Sep 28 '18 at 20:27
  • 1
    See also this Q&A for reading a file by lines: https://stackoverflow.com/questions/58169711/how-to-read-a-file-line-by-line-in-julia/58169712 – StefanKarpinski Sep 30 '19 at 14:21