Read small text file as a string


#1

This works in a code file where fname is a string that is a path to a file:

println(read(fname, String))

But, it doesn’t work in the REPL. Weird. Shouldn’t it be the same for both? I copy it from the code file and paste in the path and get:

println(read("/Users/me/Dropbox/Online Coursework/ML Independent explorations/nn by hand/nnstats-2018-07-20T10-04-45-782.txt",String))
ERROR: MethodError: Cannot `convert` an object of type Type{String} to an object of type Array{UInt8,1}
This may have arisen from a call to the constructor Array{UInt8,1}(...),
since type constructors fall back to convert methods.

From the convert error it looks like Julia is treating the string (the value of fname) as the thing to read and convert to String. But, the method should interpret the string as a filename.

There are 37 read methods and this is the only one that could match:
read(filename::AbstractString, args...) in Base at io.jl:160
Not sure if the args can be functions or a constructor function.

As an alternative, this works in the REPL: println(String(read(fname)))

I am sure it used to work. And I saw this shortcut somewhere as I wouldn’t have thought it could work. Having seen it I used it for a tiny little status file.

Again, it works perfectly in the script (actually, a function) so I am confused.


#2

Seems like a 0.6 vs 0.7 issue?


#3

These two variants work in the 0.6 and 0.7 REPLs:

julia-0.6> println(readstring("/tmp/ip-address.txt"))
121.121.31.59

julia-0.7> println(read("/tmp/ip-address.txt", String))
121.121.31.59

#4

Thanks. I am using Julia 0.6.3.

It’s a minor thing as my code works; is it typical to see a difference in the REPL?


#5

You missed the point. You are using different versions of Julia. One version in REPL and another otherwise.


#6

Compat.jl also provides the read(io, String) method in v0.6, so perhaps the script includes using Compat.


#7

I think you nailed it. I don’t directly import compat but one of the packages likely does.

  • Lewis

#8

Ah, yes. Compat does some type-piracy by implementing new methods for Base functions on Base types, so it can cause these non-local effects. We discourage type-piracy in general, but Compat is kind of special.