read() or readline() clobbers my variable

G. S. Hayes sjdevnull at yahoo.com
Fri Jul 30 13:58:25 EDT 2004


washu <me at privacy.net> wrote in message news:<pan.2004.07.30.07.43.25.978439 at privacy.net>...
> Hi,
> 
> This may be a simple problem but I can't seem to find a way around it. 
> I've pasted my code snippet below:
> 
> import os
> 
> input = os.popen("echo hello")
> input.readline()
> input.readline()
[SNIP]
> I'd like to basically freeze the contents of input for further
> manipulation or comparison.  Any ideas?

Save it in a variable.  readline is a function which reads the next
line from the open file.  Consider the following examples:

>>> import os
>>> a=os.popen('echo "hi\nthere"')
>>> print a.readline()
hi
 
>>> print a.readline()
there

>>> a=os.popen('echo "hi\nthere"')
>>> print a.readlines()
['hi\n', 'there\n']
>>> print a.readlines()
[]
>>> a=os.popen('echo "hi\nthere"')
>>> lines=a.readlines()
>>> print lines
['hi\n', 'there\n']
>>> print lines
['hi\n', 'there\n']
>>> a=os.popen('echo "hi\nthere"')
>>> line1=a.readline()
>>> line2=a.readline()
>>> print line1
hi
 
>>> print line2
there
 
>>> print line1
hi
 
>>> print line2
there



More information about the Python-list mailing list