Reading a vector string file

Hi I am trying to do a very simple operation dealing with strings (normally I work with numerical data so not too familiar with strings). I want to read in a list of names from a file called Name_List.txt (each name on one line of file as below)

A
Ma
hc

my test code is:

# Test read
name_list = String[]      # initialize empty array

open("Name_List.txt", "r") do f
    for ln in eachline(f)
        name_list[ln] == f
    
    end
end

 with error:

ERROR: LoadError: ArgumentError: invalid index: "A" of type String
Stacktrace:
 [1] to_index(i::String)
   @ Base .\indices.jl:300
 [2] to_index(A::Vector{String}, i::String)
   @ Base .\indices.jl:277
 [3] to_indices
   @ .\indices.jl:333 [inlined]
 [4] to_indices
   @ .\indices.jl:325 [inlined]
 [5] getindex(A::Vector{String}, I::String)
   @ Base .\abstractarray.jl:1170
 [6] (::var"#142#143")(f::IOStream)
   @ Main c:\Users\peter\Documents\Julia_Code\GH_Model_Final\Test_Read.jl:6
 [7] open(::var"#142#143", ::String, ::Vararg{String, N} where N; kwargs::Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}})
   @ Base .\io.jl:330
 [8] open(::Function, ::String, ::String)
   @ Base .\io.jl:328
 [9] top-level scope
   @ c:\Users\peter\Documents\Julia_Code\GH_Model_Final\Test_Read.jl:4
in expression starting at c:\Users\peter\Documents\Julia_Code\GH_Model_Final\Test_Read.jl:4

Hope someone can set me straight. Thanks

try

name_list = String[]      # initialize empty array

open("Name_List.txt", "r") do f
    for ln in eachline(f)
        push!(name_list,ln)
    end
end

That worked. Many thanks for quick response. Peter

You can also just use the built-in readlines function to read all the lines into an array of strings in a single call.

2 Likes

Thanks