From: Matteo Landi on
Ops I miss the "one line" request, so my previous answer was definitely OT.

glob seems to be your solution.

On Tue, Aug 3, 2010 at 12:44 PM, Rory Campbell-Lange
<rory(a)campbell-lange.net> wrote:
> On 03/08/10, Alex Willmer (alex(a)moreati.org.uk) wrote:
>> On Aug 3, 11:21?am, loial <jldunn2...(a)gmail.com> wrote:
>> > 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?
>>
>> import glob
>> my_files = glob.glob('/home/mydir/JOHN*.xml')
>
> import os; my_files = [f for f in os.listdir('/home/mydir/') if 'JOHN' in f and 'xml' in f]
>
> But in fact glob uses os.listdir and fnmatch.fnmatch functions
> internally, so is definitely the way to go.
>
> http://docs.python.org/library/glob.html
>
> --
> Rory Campbell-Lange
> rory(a)campbell-lange.net
> --
> http://mail.python.org/mailman/listinfo/python-list
>



--
Matteo Landi
http://www.matteolandi.net/
From: Steven W. Orr on
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

First  |  Prev  | 
Pages: 1 2
Prev: PIL
Next: I GOT $2500 FROM PAYPAL....