Am 20.02.16 um 19:45 schrieb wrong.addres...@gmail.com:
On Saturday, 20 February 2016 09:54:15 UTC+2, Steven D'Aprano  wrote:
To answer your question "Do I need something fancy...?", no, of course not,
reading a line of numbers from a text file is easy.

with open("numbers.txt", "r") as f:
     for line in f:
         numbers = [int(s) for s in split(line)]


This looks good enough. This does not seem complicated (although I still 
understand almost nothing of what is written). I was simply not expressing 
myself in a way you people would understand.


will read and convert integer-valued numbers separated by whitespace like:

     123 654 9374 1 -45 3625


one line at a time. You can then collate them for later use, or process them
as you go. If they're floating point numbers, change the call to int() to a
call to float().


And I guess if the first three numbers are integers and the fourth is a float, 
then also there must be some equally straightforward way.

If you know in advance, what you expect, then it is easy. Most people who gave you answers assumed that you have a messy file and don't know if an int or float follows, and you want a program which decides by itself whether to read an int, float or string.

Whereas, if the format is fixed, for 3 ints and 1 float, you could do:

str='1 2 3 3.14159' # some example
fmt=(int,int,int,float) # define format
a,b,c,d=[type(x) for (type,x) in zip(fmt, str.split())]

It's one line, but it might look involved and actually it uses a list comprehension, tuple unpacking and first class functions, so it's certainly not comprehensible from the first Python lesson. Another alternative would be sscanf. This is a 3rd party module which simulates C sscanf, optimized more or less for this kind of number parsing:

https://hkn.eecs.berkeley.edu/~dyoo/python/scanf/

After installing that, you can do:

from scanf import sscanf
str='1 2 3 3.14159'
a,b,c,d=sscanf(str, '%d %d %d %f')

whereby '%d' means integer and '%f' is float. sscanf also handles fixed-width columns which you often get from Fortran programs.

        Christian


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to