python使用glob获取文件文件夹位置和文件

2024-09-28 17:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在我的视图中搜索。opt.php文件编译的文件。在

目前我正在做这样的事情

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', ''] 
    '''

有更好的方法吗?我想

index.opt.php这样的文件名,本例中文件所在的文件夹位于../../../views/users用户中


Tags: 文件pathin视图forindexfilename事情
1条回答
网友
1楼 · 发布于 2024-09-28 17:30:51

如果你想得到你可以使用的基名和目录名操作系统路径拆分():

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

顺便说一句:glob()只在目录深度固定的情况下有效。使用手术室步行()如果您想要类似于unix“find”命令(递归目录遍历)的话。在

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

相关问题 更多 >