2016-03-28 16 views
1

このタイプの質問は以前に尋ねられましたが、 。それはすべてのファイルとディレクトリのフォルダからではなく、親フォルダ自体を削除します。Pythonはディレクトリ内のファイルやフォルダを再帰的に削除しますが、親ディレクトリや特定のフォルダは削除しません。

This questionは、ユーザーがが意図したとおりに作業を行うというコードを与えるところ、answer by user Ikerを持っています。

親ディレクトリからすべてのファイルを削除し、親ディレクトリではなく、ディレクトリ内のフォルダを除外したい場合は、これをさらに調整する必要があります。私は基本的に言う声明「の」後「であれば」文の追加しようとしている

import os 
import shutil 

files = '[the path to my folder]' 

for root, dirs, files in os.walk(files): 
    for f in files: 
     os.unlink(os.path.join(root, f)) 
    for d in dirs: 
     shutil.rmtree(os.path.join(root, d)) 

::!

ファイル場合を=

を保つ

私が使用しているコードがあります親ファイル内の "keep"という名前の変数を "keep"に設定すると、このスクリプトは親ディレクトリ以外のすべてを削除し、親ディレクトリ内の "keep"というディレクトリを削除します。しかし、それを加えた後、コードは機能しません。ここで

は私が持っていた正確なコードは、コードを壊しif文で、次のとおりです。私は私がやっていると確信している

import os 
import shutil 

files = '[the path to the parent folder' 
keep = '[the path to the "keep" folder]' 

for root, dirs, files in os.walk(files): 
    for f in files: 
     if files != keep: 
      os.unlink(os.path.join(root, f)) 
    for d in dirs: 
     if files != keep: 
      shutil.rmtree(os.path.join(root, d)) 

ので、非常に明白ですが、それは私には明らかにされていませんどんな助けもありがとう。

ありがとうございます!

EDIT:以下ベンの答えに基づいて、ここに私のために働いていたコードは次のとおりです。

import os 
import shutil 

root_dir = r'[path to directory]' # Directory to scan/delete 

keep = 'keep' # name of file in directory to not be deleted 

for root, dirs, files in os.walk(root_dir): 
    for name in files: 
     # make sure what you want to keep isn't in the full filename 
     if (keep not in root and keep not in name): 
      os.unlink(os.path.join(root, name)) # Deletes files not in 'keep' folder 
    for name in dirs: 
     if (keep not in root and keep not in name): 
      shutil.rmtree(os.path.join(root, name)) # Deletes directories not in 'keep' folder 

答えて

0

私は平等をチェックするが、あなたのパスに保存しておきたいフォルダが含まれているかどうかではないでしょう。あなたのkeepがどのように詳細に応じて、これは消去したいいくつかのファイルを消去しないことがあります:rm_me\keep.txtもかかわらず、保持されます。この例では、docs(それを見るために少しスクロールアップ)

import os 

# change this, obviously 
root_dir = r'C:\Users\ben\Documents\Python Scripts\tmp' 

keep = 'keep' 

for root, dirs, files in os.walk(root_dir): 
    for name in files: 
     # make sure what you want to keep isn't in the full filename 
     if (keep not in root and keep not in name): 
      print(os.path.join(root, name)) #change to os.remove once sure 
    for name in dirs: 
     if (keep not in root and keep not in name): 
      print(os.path.join(root, name)) # change to os.rmdir once sure 

ノートから構成されていますそれは正しいディレクトリにはありません。詳細なフォルダ名はこれを助けることができます:keepがr'C:\very_specific'のようなものなら、それはファイルの名前ではなく、必要なものをすべて消去します。

+0

ありがとうございました!それは素晴らしい仕事でした。あなたの答えに基づいて動作するコードで質問を更新しています。 – redjax

関連する問題