0

hello im doing a search in my views for .opt.php files that are compiled.

currently im doing something like this

for x in glob.glob(PATH_VIEWS + '*.opt.php'):

    # Get file names
    segment1 = x.split('/')
    filename = segment1[-1]
    realname = filename.split('.opt.php')
    appfolder = segment1[-4]
    folder = segment1[-2]

    ''' ../../../views/users/index.opt.php
    ['..', '..', '..', 'views', 'users', 'index.opt.php']
    index.opt.php
    ['index', ''] 
    '''

is there a better way to do this? i would like to get

filename like index.opt.php and the folders that the files are in in this example is in ../../../views/users users

3
  • What is PATH_VIEWS? Isn't it the directory name you are looking for? Commented Dec 21, 2011 at 13:58
  • its a variable in this case ../../../views/ what im looking for is ../../../views/[*]/filename the one in the square. Commented Dec 21, 2011 at 14:01
  • yup im looking for the directory name. in this cae its users. Commented Dec 21, 2011 at 14:12

1 Answer 1

2

If you want to get the basename and the dirname you can use os.path.split():

http://docs.python.org/library/os.path.html#os.path.split

BTW: glob() only works if directory depth is fixed. Use os.walk() if you want something like the unix "find" command (recursive directory walk).

import os, glob
magic='.log'
for file in glob.glob(os.path.join(mydir, '*%s' % magic)):
    dirname, filename = os.path.split(file)
    base=filename[:-len(magic)] # if you use this very often, it is faster to use a variable "len_magic"
    print dirname, base
Sign up to request clarification or add additional context in comments.

2 Comments

wew how does the *%s does? and baout os.walk can you give me a example ? thank you so much, im still googling how the magic work :)
"magic" is just a variable name. I could have named it "boring", too. I tested the script with log-files. Your file extension was different. Docs are here: docs.python.org/library/os.html#os.walk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.