在Python中查找os.walk()中的文件路径

时间:2017-02-19 02:40:30

标签: python-3.x os.walk

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$',views.search, name='search'),]

我怎样才能找到文件的绝对路径并将其传递给os.unlink(path)??? .nfo文件可以是SomePath / folder / subfolder / file吗?

os.unlink(os.path.abspath(filename))无济于事。 如果我尝试glob.glob,它将只搜索当前目录(SomePath上的文件夹)。

2 个答案:

答案 0 :(得分:0)

import os
for folder, subfolder, file in os.walk('SomePath'):
 for filename in file:
    if filename.endswith('.srt'):
        os.unlink(os.path.join(folder,filename))

看起来像上面的工作。如果现在我用print(文件名)替换最后一行,我没有得到.srt文件列表

答案 1 :(得分:0)

要获取目录和/或子目录的所有文件,我在许多项目中重用以下代码:

import os
def get_all_files(rootdir, mindepth = 1, maxdepth = float('inf')):
    """
    Usage:

    d = get_all_files(rootdir, mindepth = 1, maxdepth = 2)

    This returns a list of all files of a directory, including all files in
    subdirectories. Full paths are returned.

    WARNING: this may create a very large list if many files exists in the 
    directory and subdirectories. Make sure you set the maxdepth appropriately.

    rootdir  = existing directory to start
    mindepth = int: the level to start, 1 is start at root dir, 2 is start 
               at the sub direcories of the root dir, and-so-on-so-forth.
    maxdepth = int: the level which to report to. Example, if you only want 
               in the files of the sub directories of the root dir, 
               set mindepth = 2 and maxdepth = 2. If you only want the files
               of the root dir itself, set mindepth = 1 and maxdepth = 1
    """
    rootdir = os.path.normcase(rootdir)
    file_paths = []
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                file_paths.append(os.path.join(dirpath, filename))
        elif depth > maxdepth:
            del dirs[:]  
    return file_paths

之后,无论如何都可以过滤,切片和切块。如果您想要在此例程中进行过滤,则可以在for filename in files:之后和file_paths.append(os.path.join(dirpath, filename))

之前进行过滤

HTH。