Easy way to read input from a file

I need to read the input from the next input file and initialize all the variables.

Input file

A=1.0
B=1.0
C=2.0

I am using the following code Juliato read this.

# Read the delemited file
in = readdlm("inputFile.in",'=');
# Declare all the variables before initialising them with the data from input file.
A=0.0; B=0.0; C=0.0;
# Parsing
for i in 1:length(in[:,1])
  if in[i,1] == "A"
    A=in[i,2]
  elseif in[i,1] == "B"
    B=in[i,2]
  elseif in[i,1] == "C"
    C=in[i,2]
  else
    println(STDERR,in[i,1],"\tKeyword not recognised.")
    exit()
  end
end

This method is not scalable for a large number of input variables. As you noticed, I want to read the names of variables and initialize them with the value specified in the input file.

Is there a more elegant / short way to do this? I want to store variable names in an array and use a loop forto read them from a file.

Thank you for your help.

+4
source share
3 answers

Maybe so?

Basic approach

config.txt,

A=1.0
B = 2.1
C= 3.3
D =4.4

, , Dict, :

julia> vars = Dict{String, Float64}()
Dict{String,Float64} with 0 entries

julia> f = open("config.txt")
IOStream(<file config.txt>)

julia> for line in eachline(f)
           var, val = split(line, "=")
           vars[strip(var)] = parse(Float64, val)
       end

julia> vars
Dict{String,Float64} with 4 entries:
  "B" => 2.1
  "A" => 1.0
  "C" => 3.3
  "D" => 4.4

julia> vars["A"]
1.0

, , :

julia> vars = Dict{String, Float64}()
Dict{String,Float64} with 0 entries

julia> allowed = ["A", "B", "C"]
3-element Array{String,1}:
 "A"
 "B"
 "C"

julia> f = open("config.txt")
IOStream(<file config.txt>)

julia> for line in eachline(f)
           var, val = split(line, "=")
           stripped = strip(var)
           if stripped in allowed
               vars[stripped] = parse(Float64, val)
           end
       end

julia> vars
Dict{String,Float64} with 3 entries:
  "B" => 2.1
  "A" => 1.0
  "C" => 3.3

D=... config.txt , allowed.

, Dict

:

function go(;A=0.0, B=0.0, C=0.0)
        println("A = $A, B = $B, C = $C")
end

vars = Dict{Symbol, Float64}()

f = open("config.txt")
allowed = ["A", "B", "C"]

for line in eachline(f)
    var, val = split(line, "=")
    stripped = strip(var)
    if stripped in allowed
        vars[Symbol(stripped)] = parse(Float64, val)
    end
end

go(;vars...)

config.txt

A = 1.0, B = 2.1, C = 3.3
+4

, , , ( / ).

inputfile = readlines("inputFile.in")
eval.(parse.(inputfile))

, for, ? , - :

open("inputFile.in", "r") do f
    for line in eachline(f)
        eval(parse(line))
    end
end

, JLD .

using JLD

A=1.0
B=1.0
C=2.0

@save "myfirstsave.jld" A B C
@load "myfirstsave.jld"
+1

, :

include("inputFile.in")

println("A", A)

, JLD, , , , .

, , . , ..

+1

Source: https://habr.com/ru/post/1670908/


All Articles