Python: Save element by element from input
<p>I have an input file as follow</p>

<pre><code>0.1 #real number
0.2 #real number
Hello #string
10000 #integer number
</code></pre>

<p>I want to read it and use each line, before the '#' symbol, in my code. For the second part I did</p>

<pre><code>with open('input.dat') as f:
    for line in f:
        line = line.split('#', 1)[0]
        line = line.rstrip()
        print(line) #test print
f.close()
</code></pre>

<p>In this case I can read and print the number/string before the '#' symbol, but what about save them?
For instance if I want to save 'Hello' in a string called 'name', '0.1' as a real called 'min' and so on.
The simplest way I found, to read the input.dat file and save the elements as I want is </p>

<pre><code>with open('input.dat') as f:
    lines = f.readlines()
f.close()

min=lines[2] # it print me: "0.1 #real number"
</code></pre>

<p>But what about only <code>min=0.1</code>, how can I obtain both the reading and saving procedure ? I am noob in python so maybe I lack of basics.</p>

<p>Many thanks</p>

<p>One way to do it is to store the results in an array. What to do next will depend on how your input is structured: will it always contain just four values of those types and in that order?</p>

<pre><code>values = []
with open('input.dat') as f:
    for line in f:
        value = line.split('#', 1)[0]

        if value.isdigit():
            values.append(int(value))
        else:
            try:
                values.append(float(value))
            except ValueError:
                values.append(value)
</code></pre>

<p>If the values always appear in that order, you can then do something like this:</p>

<pre><code>n_min, n_max, name, big_number = values
</code></pre>

<p>(note: try to avoid naming variables <code>min</code>, <code>max</code> or other built-in keywords since that might cause problems later on!)</p>

python string file input