2017-02-19 64 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 /文件夾/子文件夾/文件?在Python中的os.walk()中查找文件路徑

os.unlink(os.path.abspath(filename))不起作用。 如果我嘗試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)) 

看起來像上面的工作。如果現在我用打印(文件名)替換最後一行,我沒有得到.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。