reading file to list

Tino Wildenhain tino at wildenhain.de
Sat Jan 17 13:25:12 EST 2009


MRAB wrote:
> Tino Wildenhain wrote:
>> Xah Lee wrote:
>>> comp.lang.lisp,comp.lang.scheme,comp.lang.functional,comp.lang.python,comp.lang.ruby 
>>>
>>>
>> ...
>>> OK, I want to create a nested list in Lisp (always of only integers)
>>> from a text file, such that each line in the text file would be
>>> represented as a sublist in the 'imported' list.
>>>
>>> example of a file's content
>>>
>>> 3 10 2
>>> 4 1
>>> 11 18
>>>
>>> example of programing behavior
>>> (make-list-from-text "blob.txt") => ((3 10 2) (4 1) (11 18))
>>
>>>
>>> In a show-off context, it can be reduced to by about 50%, but still
>>> far verbose than ruby or say perl (which is 1 or 2 lines. (python
>>> would be 3 or 5)).
>>
>> So? Please count the lines:
>>
>> [line.strip().split() for line in file("blob.txt")]
>>
> The original requirement was for a list of lists of integers:

Actually I read:
"Note that the result element is string, not numbers. There's no easy
way to convert them on the fly. 3 or so more lines will be needed to
do that."

So I felt that requirement was dropped, but otherwise, you are right :-)

> [[int(x) for x in line.split()] for line in open("blob.txt")]
> 
> Still only 1 line, though.

Yep.

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090117/435bb901/attachment-0001.bin>


More information about the Python-list mailing list