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/folder/subfolder/fileのような場所にありますか?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)) 

上記のように見えます。最後の行をprint(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の前になります。

関連する問題