2017-05-19 7 views
0

ディレクトリ内に「.tmp」という拡張子を持つフォルダを見つけようとしています。サブディレクトリ)。基本的には、特定のパスのどこにでも拡張子が「.tmp」のフォルダです。特定のディレクトリとそのサブディレクトリで、拡張子.tmpで終わるすべてのフォルダを見つけよう

現在のところ、特定のディレクトリでは拡張子.tmpのフォルダしか見つけられませんが、後続のディレクトリでは見つかりません。親切に助けてください。

コード:

def main(): 
    """The first function to be executed. 
    Changes the directory. In a particular directory and subdirectories, find 
    all the folders ending with .tmp extension and notify the user that it is 
    existing from a particular date. 
    """ 
    body = "Email body" 
    subject = "Subject for the email" 
    to_email = "[email protected]" 

    # Change the directory 
    os.chdir('/remote/us01home53/subburat/cn-alert/') 

    # print [name for name in os.listdir(".") if os.path.isdir(name)] 
    for name in os.listdir("."): 
     if os.path.isdir(name): 
      now = time.time() 
      if name.endswith('.tmp'): 
       if (now - os.path.getmtime(name)) > (1*60*60): 
        print('%s folder is older. Created at %s' % 
          (name, os.path.getmtime(name))) 
        print('Sending email...') 
        send_email(body, subject, to_email) 
        print('Email sent.') 


if __name__ == '__main__': 
    main() 

オペレーティングシステム:Linux;あなたがPythonの3.xを使用しているので プログラミング言語Pythonは

+0

あなたは.tmpファイルのディレクトリ内の.tmpファイルを持つすべてのサブディレクトリのみのものを見つけたいですか?例えば[./test1.tmp、./test2/test3.tmp]対[./test1.tmp] – Robb

+0

'os.walk'をチェックしてください。 –

+0

@Robb '.tmp' extension.e.gを持つすべてのサブディレクトリを探したい。 [1.tmp、test/2.tmp、test1/test2/3.tmp]。 –

答えて

0

os.walk()メソッドを使用して、.tmpで終わるすべてのディレクトリを見つけることができました。以下に示すのは、

は、私はこれを実現するために使用するコードです:

import os 
import time 
import sys 


def send_email(body, subject, to_email): 
    """This function sends an email 

    Args: 
     body (str): Body of email 
     subject (str): Subject of email 
     to_email (str): Recepient (receiver) of email 

    Returns: 
     An email to the receiver with the given subject and body. 

    """ 
    return os.system('printf "' + body + '" | mail -s "' 
        + subject + '" ' + to_email) 


def find_tmp(path_): 
    """ 
    In a particular directory and subdirectories, find all the folders ending 
    with .tmp extension and notify the user that it is existing from a 
    particular date. 
    """ 
    subject = 'Clarity now scan not finished.' 
    body = '' 
    emails = ['[email protected]'] 

    now = time.time() 

    for root, dirs, files in os.walk(".", topdown=True): 
     for dir_name in dirs: 
      if dir_name.endswith('.tmp'): 
       full_path = os.path.join(root, dir_name) 

       mtime = os.stat(full_path).st_mtime 

       if (now - mtime) > (1*60): 
        body += full_path + '\n' 


    # Send email to all the people in email list 
    for email in emails: 
     print('Sending email..') 
     send_email(body, subject, email) 
     print('Email sent') 


def main(): 
    find_tmp('.') 


if __name__ == '__main__': 
    main() 
3

、あなたは試すことがpathlib.Path.rglob EDIT

pathlib.Path('.').rglob('*.tmp') 

私はそれぞれの結果は、のインスタンスになることを追加することを忘れてしまいましたpathlib.Pathサブクラスのように、ディレクトリ全体の選択は、それほど単純でなければなりません。

[p.is_dir() for p in pathlib.Path('.').rglob('*.tmp')] 
+1

これはPython 2.7.xでも動作します( 'pathlib2')... –

+0

ありがとう、@ l'L'l、私は最近、3.xでそれを学びましたが、数ヶ月間2.7に触れていません。 _os、walk)と_os.path_ stuff – volcano

+0

はい、間違いなく!'pathlib'モジュールは実際にこのタイプのタスクに使用するのに最適なものです。あなたの答えが正しいものに選ばれていないのは驚きです。 –

0

あなたのプログラムでは、 "。"の付いていない項目がある場合は、そのディレクトリをディレクトリと見なすことができます(もしそうでなければ、これは動作しません)。このパス/名前をデータ構造のようなStackに入れて、現在のディレクトリが完成したら、スタックの一番上をつかんで同じことをします。

2

ファイルを再帰的にリストすることに関する既存の質問があります。彼らはglobモジュールを使用して、このような機能を実現しています。以下はその例です。

import glob 

files = glob.glob(PATH + '/**/*.tmp', recursive=True) 

ここで、PATHは検索を開始するルートディレクトリです。あなたの既存のコードを取り、それ自身の機能に検索をオフに分割した場合(このanswerから適応)

+0

Python 3.5 –

+1

'glob.glob(PATH + ')の使用に基づいて、 /**/*.tmp '、recursive = True) 'は既にリストを返します。あなたは理解する必要はありません。 – EFT

+0

@Benedict Bunting私はファイルではなく '.tmp'で終わるフォルダを探しています。それもそれのために働くのですか? –

1

あなたがして再帰的に呼び出すことができます。これは、あなたが調べることができるようになります

def find_tmp(path_): 
    for name in os.listdir(path_): 
     full_name = os.path.join(path_, name) 
     if os.path.isdir(full_name): 
      if name.endswith('.tmp'): 
       print("found: {0}".format(full_name)) 
       # your other operations 
      find_tmp(full_name) 

def main(): 
    ... 
    find_tmp('.') 

各サブディレクトリの結果のディレクトリ。

+0

お世話になりました!それは魅力のように機能します:) –

+1

キエフの違反に悪影響を及ぼし、ホイールを改革します。 – volcano

+0

ホイールの再発明について真です。最初にos.walkまたはglobパターンのいずれかを使って関連するすべてのアイテムを検索すると、それが処理されて読みやすくなり、Pythonになります。私の答えでは、なぜそこにあったものが完全に機能しなかったのかを強調したかったのです。 – Robb

関連する問題