简体   繁体   中英

python get file folder location and file with glob

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM