2017-02-19 5 views
0
import os 
    for folder, subfolder, file in os.walk ('SomePath'): 
    for filename in file: 
     if filename.endswith('.nfo'): 
      os.unlink(path) 

Как я могу найти абсолютный путь файла и передать его в os.unlink (путь) ??? .nfo файл может быть где угодно, как SomePath/папка/подпапка/файл?найти путь к файлу в os.walk() в Python

os.unlink (os.path.abspath (имя файла)) не поможет. Если я попробую glob.glob, он будет просто искать текущий каталог (папка в SomePath).

ответ

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)) 

выглядит выше обработанный. если теперь я заменяю последнюю строку печатью (filename), я не получаю список файлов .srt

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.