Reading values from .txt file

Hello, I am exporting certain values from Python into a txt file using the following command:

a = np.random.rand(2)

np.savetxt('a.txt',a)

How can I call this .txt file from Julia and store the value into a variable?

For this simple case (a single column vector)

julia> a = open("a.txt") do f
           readlines(f) |> (s->parse.(Float64, s))
       end
2-element Vector{Float64}:
 0.9445125367265572
 0.10241256516487685

For more complicated cases, the DelimitedFiles standard library is a good start.

May also consider the one-liner:

a = parse.(Float64, readlines("a.txt"))

But the simpler is:

using DelimitedFiles
a = readdlm("a.txt")
4 Likes

Awesome, thank you!

In that same thread, I have another question.

I have a list b that contains the following values:

b = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]

I save it to a text file with the following commands

with open('b.txt', 'w') as value:
    for item in b:
        value.write(f"{item}\n")

How do I read a list from a text file in Julia?

I tried the previous commands stated in this thread, and they do not work.

When I execute the following command in Julia:

b = open("b.txt") do f
            readlines(f)
       end

I get the following result:

"(0, 0)"
 "(0, 1)"
 "(0, 2)"
 "(0, 3)"
 "(0, 4)"
 "(0, 5)"

How do I get the result without the quotation marks?

Any particular reason for using a txt file? You could skip manual parsing entirely by using GitHub - fhs/NPZ.jl: A Julia package that provides support for reading and writing Numpy .npy and .npz files or similar.

It looks like I learn something new every day. Thank you.

I agree that using NPZ.jl is a better solution, but to answer the question as asked:

function readtuples(filename)
    tvec = Tuple{Int, Int}[]
    for line in eachline(filename)
        words = split(line, ('(', ',', ')'), keepempty=false)
        push!(tvec, tuple(parse.(Int, words)...))
    end
    return tvec
end

which can be used as follows:

julia> readtuples("data.txt")
6-element Vector{Tuple{Int64, Int64}}:
 (0, 0)
 (0, 1)
 (0, 2)
 (0, 3)
 (0, 4)
 (0, 5)
2 Likes

Also, a regex one-liner:

[Tuple(parse.(Int, match(r"\((.*),(.*)\)", l).captures)) for l in eachline(file)]

where:
file = "b.txt"

1 Like