reading data from a file

Stuart Reynolds S.I.Reynolds at cs.bham.ac.uk
Wed Apr 5 09:01:28 EDT 2000


Hi Dave,

dave white wrote:
> 
> Hello, can anyone please help with these basic questions:
> 
> 1)  I'm using file.readlines() to read in some data.  Is there any quick
> and efficient way to automatically get rid of the endofline '\012'
> character that gets appended to the strings at the end of every line?
 
  text = text[:-1]

Will chop off the last character of any sequence object.


> 2)  Is there a way for python to read a line from a file in such a way
> that it knows its a collection data type and not just a string? i.e.
> read something like [[1,2][3,4][5,6]] and know its a list of lists?
> 


--- pyfile.txt ----
"Nobody expects the Spanish Inquisition"
["Cat","Dog", 42]
99
99.0
----- read it in

for line in  open("pyfile.txt").readlines():
    obj = eval(line)
    print type(obj), obj
----

This prints out,

 <type 'string'> Nobody expects the Spanish Inquisition
 <type 'list'> ['Cat', 'Dog', 42]
 <type 'int'> 99
 <type 'float'> 99.0




Stuart



More information about the Python-list mailing list