Adding file to vector claims in is a char, but typeof(file) is string

I have this code

filenames = Vector{String}()
for file in readdir()
    println(typeof(file))
    append!(filenames,file)
end

which generates an error:

MethodError: Cannot `convert` an object of type Char to an object of type String
Closest candidates are:
  convert(::Type{String}, ::String) at essentials.jl:210
  convert(::Type{T}, ::T) where T<:AbstractString at strings/basic.jl:231
  convert(::Type{T}, ::AbstractString) where T<:AbstractString at strings/basic.jl:232
  ...

Stacktrace:
 [1] setindex!(A::Vector{String}, x::Char, i1::Int64)
   @ Base ./array.jl:839
 [2] _append!(a::Vector{String}, #unused#::Base.HasLength, iter::String)
   @ Base ./array.jl:991
 [3] append!(a::Vector{String}, iter::String)
   @ Base ./array.jl:981
 [4] top-level scope
   @ ./In[21]:4
 [5] eval
   @ ./boot.jl:360 [inlined]
 [6] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1094

The confusing part is that the print message is String. So file is first a String, but when I try to add it to the vector, it is a Char? What is going on?

Collections and Data Structures · The Julia Language!

The elements of file (ie., chars) are appended to filename. You probably want push! instead.

2 Likes

Ahh!
Thanks a lot, I totally get it now!

And if its not a MWE just use:

filenames=readdir()
1 Like