[Tutor] Fwd: Re: Python 3.6 Extract Floating Point Data from a Text File

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 1 13:16:57 EDT 2017


On 01/05/17 15:54, Stephen P. Molnar wrote:
> Unfortunately, I'm still missing something. Here is my latest attempt
> to incorporate your solution:
> name = input("Enter Molecule ID: ")
> name = str(name)
you don't need the str() since input() always returns whatever string
the user enters.

> name_in = []
> name_in = name[:]+'.lac.dat'

You don't need the [:] either since that just makes a copy of name.
So you can just use

name_in = name + '.lac.dat'

But notice that you have lost the list you created. name_in
is now just a string.
> atm_chg = []

This creates a new empty list.
But...

> with open(name_in) as f:
>      # skip two lines
>      f.readline()
>      f.readline()
>      for line in f.readlines():
You don't need readlines, you can just iterate over f:

for line in f:
    atm_chg = float(line.split()[-1])

This loses the list you created earlier and replaces it with a float.
I suspect you want to append this to your list?

    atm_chg.append(float(line.split()[-1])

> The error this attempt give me is attached.
>
> IndexError: list index out of range

That's only the last line of the error. Please always post the
full error text. There is a lot of useful data in there that we
can't see. As a debug step you could try printing line to
make sure it always contains multiple fields.

But are you sure that you only want a list of floats out?
Steven's solution based on a dictionary seemed like it
might be more useful for you?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list