os.path.isfile and wildcard for directory name

Discussion in 'Python' started by smainklh@free.fr, Dec 30, 2010.

  1. Guest

    Hi everyone,

    I'm just beginning to learn python language and i'm trying to do something and i
    can't figure it out.

    I want to test if a file exists but my path contain a directory name that
    differs from a server to another.
    In shell i would have done something like that :

    #!/bin/bash

    mypath=/dire*/directory02/
    myfile=filename

    myfile=toto

    if [ -f $mypath/$myfile ]
    then
    echo "File $file exists"
    fi


    How can i do the same thing (wildcard in a directory name) in python please ?

    Thanks for your help !

    Smaine
    , Dec 30, 2010
    #1
    1. Advertising

  2. Peter Otten Guest

    wrote:

    > I'm just beginning to learn python language and i'm trying to do something
    > and i can't figure it out.
    >
    > I want to test if a file exists but my path contain a directory name that
    > differs from a server to another.
    > In shell i would have done something like that :
    >
    > #!/bin/bash
    >
    > mypath=/dire*/directory02/
    > myfile=filename
    >
    > myfile=toto
    >
    > if [ -f $mypath/$myfile ]
    > then
    > echo "File $file exists"
    > fi
    >
    >
    > How can i do the same thing (wildcard in a directory name) in python
    > please ?


    Given

    $ mkdir yadda{1..10}
    $ touch yadda{5,7}/alpha
    $ mkdir yadda{2,4}/alpha

    You can get a list of candidates with

    >>> import glob
    >>> candidates = glob.glob("yadda*/alpha")
    >>> candidates

    ['yadda5/alpha', 'yadda2/alpha', 'yadda4/alpha', 'yadda7/alpha']

    and then use isfile() to find the actual files:

    >>> import os
    >>> [f for f in candidates if os.path.isfile(f)]

    ['yadda5/alpha', 'yadda7/alpha']

    Peter
    Peter Otten, Dec 30, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve Holden

    Re: os.path.isfile with *.tar.gz

    Steve Holden, Mar 15, 2007, in forum: Python
    Replies:
    1
    Views:
    326
    Bruno Desthuilliers
    Mar 15, 2007
  2. 7stud

    os.path.isfile() error

    7stud, Apr 7, 2007, in forum: Python
    Replies:
    5
    Views:
    405
    Steve Holden
    Apr 7, 2007
  3. Replies:
    10
    Views:
    520
    Paul Paterson
    Jun 6, 2007
  4. 7stud

    os.path.isfile()

    7stud, Jul 1, 2007, in forum: Python
    Replies:
    2
    Views:
    450
    7stud
    Jul 1, 2007
  5. Replies:
    7
    Views:
    831
Loading...

Share This Page