Get name of file from directory into variable

Steven W. Orr steveo at syslang.net
Wed Aug 4 11:44:12 EDT 2010


On 08/03/10 06:21, quoth loial:
> In a unix shell script I can do something like this to look in a
> directory and get the name of a file or files into a variable :
> 
> MYFILE=`ls /home/mydir/JOHN*.xml`
> 
> 
> Can I do this in one line in python?
> 

Sorry, but I just can't help myself.

Yeah, it's one shell line, but why the extra process, setup of pipes,
teardown, and all the rest when you can just say

MYFILE=/home/mydir/JOHN*.xml

After all, your way just starts a subshell which runs ls in a grandchild
process and creates a pipe to read back what the subshell writes. All the
subhell does is to run ls on what the shell globs. And without any options to
the ls command, you're just as well off by using echo instead of ls.

MYFILE=`echo /home/mydir/JOHN*.xml`

Since echo is probably a builtin, you'd be creating a child but no grandchild.

Other than that, the use of glob in python answers your question well (unless
someone wants to write up how to do it in python by use of the subprocess
module along with the glob module...)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 261 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100804/e73feda0/attachment-0001.sig>


More information about the Python-list mailing list