Get name of file from directory into variable

Matteo Landi landimatte at gmail.com
Tue Aug 3 07:14:29 EDT 2010


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 at campbell-lange.net> wrote:
> On 03/08/10, Alex Willmer (alex at moreati.org.uk) wrote:
>> On Aug 3, 11:21?am, loial <jldunn2... at 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 at campbell-lange.net
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list