Home > Net >  How to read a file in Julia like Python
How to read a file in Julia like Python

Time:01-07

Why is there a difference between these?:

# Python
f = open("./text.txt", "r")
for i in f.readlines():
   for l in i:
      print(print(l == "\n", ":", l))
f.close()
# -----------------------------

# Julia
f = open("./text.txt", "r")
while !eof(f)
    for l in readline(file)
        println(l == '\n', " : ", l)
    end
end
close(f)

The Python one outputs this:

False : h
False : e
False : l
False : l
False : o
False :  
False : W
False : o
False : r
False : l
False : d
True : 
                     <--- yep, it is as expected
False : y
False : a
False : y

The Julia one outputs this:

false : h
false : e
false : l
false : l
false : o
false :         <--- is this not a \n??
false : W
false : o
false : r
false : l
false : d
false : y
false : a
false : y

text.txt is this:

hello World
yay

As you can see the outputs are different. How can I make the Julia one behaves like the Python one? Are there other ways of reading a file in Julia?

CodePudding user response:

You can do this:

# Julia
f = open("./text.txt", "r")
while !eof(f)
    for l in readline(file, keep=true)
        println(l == '\n', " : ", l)
    end
end
close(f)

By default, it discards \n's, but you can keep them by adding keep=true.

CodePudding user response:

if you like to read a character at a time you should use readeach, e.g.

f = open("./text.txt", "r")
for l in readeach(f, Char)
     println(l == '\n', " : ", l)
end

false : h
false : e
false : l
false : l
false : o
false :  
false : w
false : o
false : r
false : l
false : d
true : 

false : y
false : a
false : y

BTW, just note that this is not an efficient way.

CodePudding user response:

Here is a more Julian (and corrected) version using the keep=true suggestion by user17558100:

open("./text.txt", "r") do f
    for l in readlines(f, keep=true)
        foreach(c->println(c == '\n', " : ",c), l)
    end
end

This do format is the same as Python's with statement and this makes sure the file is closed without an explicit close() call.

  •  Tags:  
  • Related