Python Question

Python: Save element by element from input

I have an input file as follow

0.1 #real number
0.2 #real number
Hello #string
10000 #integer number

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

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

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

with open('input.dat') as f:
lines = f.readlines()

min=lines[2] # it print me: "0.1 #real number"

But what about only
, how can I obtain both the reading and saving procedure ? I am noob in python so maybe I lack of basics.

Many thanks

Answer Source

You already have all the pieces, you just need to put them in the right places:

def remove_comment(line):
    line = line.split('#', 1)[0]
    line = line.rstrip()
    return line

with open('input.dat') as f:
    lines = [remove_comment(line) for line in f]

# no need for this: "with" takes care of it: # f.close()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download