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

boB Stepp robertvstepp at gmail.com
Sun Apr 30 11:56:59 EDT 2017


Hello Stephen!

On Sun, Apr 30, 2017 at 5:09 AM, Stephen P. Molnar
<s.molnar at sbcglobal.net> wrote:
>
> I am using the Spyder v-3.1.2 IDE and porting a FORTRAN program that I wrote
> about 20 years ago to Python  Unfortunately, I am very much a novice in
> Python .
>
> I would have managed to extract input data from another calculation (not a
> Python program) into the following text file.
>
> LOEWDIN ATOMIC CHARGES
>  ----------------------
>     0 C :   -0.780631
>     1 H :    0.114577
>     2 Br:    0.309802
>     3 Cl:    0.357316
>     4 F :   -0.001065
>
> What I need to do is extract the floating point numbers into a Python file
>
> What I need to do is extract the floating point numbers into a Python file.

It is not clear to me what you mean by "Python file" (Twice over!
~(:>)) ).  But I would think a possible outline for your problem would
be:

1)  Open your data file for reading and open another (empty) file for appending.

2)  Loop over each line of your data file, ignoring the first two lines.

3)  Process one line at a time.  Use the split() string method to
split each line on the colon.  Strip all white space from the part you
are interested in.  Append the desired part to your write file.

4)  Close the files, or, better yet, setup the above with the "with"
context manager, which will handle the file closing automatically.

If you are not familiar with file I/O in Python 3, the tutorial has a
section on it:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

It is possible your actual problem is better addressed by the csv
module in the standard library.  The docs for this are at:

https://docs.python.org/3/library/csv.html

For instance, instead of using a comma as the field separator, you
could use a colon.

As to how you want to write the extracted data, that depends on what
you really want.  The above approach suffices for writing to another
text file or  to a binary file.  If you need something different then
you need to let us know what direction you need to go.

Finally, when you need to actually use the extracted string resembling
a float, you will have to convert that string using the float()
function.

Hope that something above is helpful!

Cheers!

-- 
boB


More information about the Tutor mailing list