2016-07-04 4 views
0

ローカルドライブC:と私の2つの外部ドライブE:とF:をすべて検索する簡単なスクリプトを作成しようとしています。すべての.docxファイルに対して、それらをログに書き込みます。私は右に検索部分を持っているが、一度に1つのハードドライブだけを検索することができ、結果を.logまたは.txtファイルに書き込む方法を見つけることができない。Python検索mutipleハードドライブ

with open("log.txt","wb") as fs: 
    result = "whatever result you are getting" 
    fs.write(result) 

更新:

import fnmatch 
import os 
drives = ['C:\\','E:\\','F:\\'] 
pattern = "*.py" 

with open("log.txt","wb") as fs: 
    for rootPath in drives: 
     print "Now searching in: ",rootPath 
     for root, dirs, files in os.walk(rootPath) : 
      for filename in fnmatch.filter(files, pattern) : 
       print os.path.join(root, filename) 
       result = os.path.join(root, filename) 
       fs.write(result+"\n") 

てみ

import fnmatch 
import os 
rootPath = 'F:' 
pattern = "*.docx" 

for root, dirs, files in os.walk(rootPath): 
    for filename in fnmatch.filter(files, pattern): 
    print(os.path.join(root, filename)) 
+0

また、他の方法のため、この質問を参照してください。すべてのドライブを検索するためにはループするだけですが、Windowsはcygwinやgit-bashのようなsomethengのないディレクトリとしてドライブを含むスーパーディレクトリを提供するとは思いません。 – mdurant

+1

'' '['C:\\'、 'E:\\'、 'F:\\']' ''のようなリストを作成してルートパスを繰り返すのはなぜですか? – bhansa

+0

私のコードで、正しく挿入する方法がわからないことを私に見せてもらえますか - ありがとう:-) – user2537522

答えて

1
import fnmatch 
import os 
drives = ['C:\\','E:\\','F:\\'] 
pattern = "*.docx" 

for rootPath in drives: 
    print "Now searching in: ",rootPath 
    for root, dirs, files in os.walk(rootPath) : 
     for filename in fnmatch.filter(files, pattern) : 
      print os.path.join(root, filename) 

は次のようにファイルに結果を書き込みエラーなしで作業を行います。 はここに私の開始コードであります自分でコードを書いてから解決策を見てください。
何かを理解していないかどうか質問してください。 ( `ファイル= ...`)印刷用のドキュメントを参照して、ファイルではなく、画面に印刷する場合はsearch files in all drives using Python

+0

ありがとうございます - はい私の自己コードを書き直し、それを実行し、それは素晴らしいですが、実際には、検索結果をlog.txtファイルに書き込む方法はありますか? – user2537522

+0

ログファイルは作成されましたが、 " – user2537522

+0

これは例を提供するに過ぎず、上記のコードで' os.path.join(root、filename) 'から得られた結果を書きます。変数 'result'に代入する値はすべてファイルに書き出されます。 – bhansa