os.path.isfile and wildcard for directory name

S

smainklh

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
 
P

Peter Otten

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
['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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,048
Members
48,769
Latest member
Clifft

Latest Threads

Top