parsing a file [newbie]
Alex Martelli
aleaxit at yahoo.com
Wed Jan 17 04:50:32 EST 2001
"Langa Kentane" <LangaK at discoveryhealth.co.za> wrote in message
news:mailman.979720698.24494.python-list at python.org...
> How do I read a file.
You open it for reading, then apply to the resulting Python fileobject
its methods read (to get all bytes, or up to N bytes), readline (to get
one line at a time) or readlines (to get all lines, or lines accounting
for up to N bytes).
> This is what I want to do.
> Run a command using os.popen and store the file info that it returns to x
So far, so pretty easy:
x = os.popen(thecommand, "r")
> Open file x and read the contents.[ contents of x will be a mount output.]
x is already open. You can read it with readline, read, readlines, ...
> Go to the third column of the mount output and and store in y
Presumably you want the third column _of each line_, right? Simplest
way (avoiding the intermediate variable 'x') would be one statement:
y = [line.split()[2] for line in os.popen(thecommand, "r").readlines()]
If you insist on using x, you'll need two statements:
x = os.popen(thecommand, "r")
y = [line.split()[2] for line in x.readlines()]
Alex
More information about the Python-list
mailing list