質問

Pythonでローカルフォルダーの内容を削除するにはどうすればよいですか

現在のプロジェクトはWindows用ですが、* nixも見たいです。

役に立ちましたか?

解決

ファイルのみを削除し、コメントで提案されている os.path.join()メソッドを使用するように更新されました。サブディレクトリも削除する場合は、 elif ステートメントのコメントを解除します。

import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
    file_path = os.path.join(folder, the_file)
    try:
        if os.path.isfile(file_path):
            os.unlink(file_path)
        #elif os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
        print(e)

他のヒント

shutilモジュールを試す

import shutil
shutil.rmtree('/path/to/folder')
  

説明: shutil.rmtree(path、ignore_errors = False、onerror = None)

     

Docstring:再帰的に削除   ディレクトリツリー。

     

ignore_errors が設定されている場合、エラーは   無視された;それ以外の場合、 onerror が設定されていると、   エラーを処理するために呼び出されます   引数(func、path、exc_info)ここで    func os.listdir os.remove 、または    os.rmdir ;パスはその引数です   失敗の原因となった機能。そして    exc_info は、以下によって返されるタプルです。    sys.exc_info() ignore_errors が   falseおよび onerror None 、   例外が発生します。

重要な注意: shutil.rmtree()は、ターゲットフォルダーの内容を削除するだけではないことに注意してください。フォルダー自体も削除します。

これを行うことができます:

import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)

もちろん、パスに他のフィルターを使用できます。たとえば、/ YOU / PATH / *。txtを使用すると、ディレクトリ内のすべてのテキストファイルを削除できます。

mhawkeの答えを拡大して、これを実装しました。フォルダのすべてのコンテンツは削除されますが、フォルダ自体は削除されません。 Linuxでファイル、フォルダー、シンボリックリンクを使用してテストすると、Windowsでも動作するはずです。

import os
import shutil

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

rmtree を使用してフォルダーを再作成しても機能しますが、ネットワークドライブ上のフォルダーを削除してすぐに再作成するとエラーが発生しました。

walkを使用して提案されたソリューションは、 rmtree を使用してフォルダーを削除し、以前にそれらのフォルダーにあったファイルに対して os.unlink を使用しようとするため、機能しません。 。これによりエラーが発生します。

投稿された glob ソリューションは、空ではないフォルダーを削除しようとするため、エラーが発生します。

使用することをお勧めします:

folder_path = '/path/to/folder'
for file_object in os.listdir(folder_path):
    file_object_path = os.path.join(folder_path, file_object)
    if os.path.isfile(file_object_path):
        os.unlink(file_object_path)
    else:
        shutil.rmtree(file_object_path)

これは、これまでのところ唯一の答えです。

  • すべてのシンボリックリンクを削除します
    • デッドリンク
    • ディレクトリへのリンク
    • ファイルへのリンク
  • サブディレクトリを削除
  • 親ディレクトリを削除しません

コード:

for filename in os.listdir(dirpath):
    filepath = os.path.join(dirpath, filename)
    try:
        shutil.rmtree(filepath)
    except OSError:
        os.remove(filepath)

他の多くの回答と同様に、これはパーミッションを調整してファイル/ディレクトリの削除を有効にしようとしません。

ワンライナーとして:

import os

# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

ファイルとディレクトリを考慮したより堅牢なソリューションは(2.7)です:

def rm(f):
    if os.path.isdir(f): return os.rmdir(f)
    if os.path.isfile(f): return os.unlink(f)
    raise TypeError, 'must be either file or directory'

map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

注:誰かが私の答えに反対票を投じた場合、ここで説明することがあります。

  1. 誰もが短い「n」の簡単な答えが好きです。ただし、現実はそれほど単純ではない場合があります。
  2. 答えに戻ります。 shutil.rmtree()を使用してディレクトリツリーを削除できることは知っています。私は自分のプロジェクトで何度も使ってきました。ただし、ディレクトリ自体も shutil.rmtree() によって削除されることに注意する必要があります。これは一部の人には受け入れられるかもしれませんが、フォルダの内容を削除する(副作用なし)の有効な答えではありません。
  3. 副作用の例を示します。 カスタマイズ所有者とモードビットのあるディレクトリがあり、そこに多くのコンテンツがあると仮定します。次に、 shutil.rmtree()で削除し、 os.mkdir()で再構築します。そして、代わりに default (継承)所有者とモードビットを持つ空のディレクトリを取得します。内容やディレクトリを削除する権限を持っている場合でも、ディレクトリの元の所有者とモードビットを元に戻すことができない場合があります(たとえば、スーパーユーザーではありません)。
  4. 最後に、辛抱強くコードを読む。長くて見苦しい(見えている)が、信頼性が高く効率的(使用中)であることが証明されている。

これは長くていですが、信頼性が高く効率的なソリューションです。

他の回答者が対処していないいくつかの問題を解決します。

  • シンボリックリンク上で shutil.rmtree()を呼び出さないことを含め、シンボリックリンクを正しく処理します( os.path.isdir()テストに合格します)ディレクトリへのリンク; os.walk()の結果にも、シンボリックリンクディレクトリも含まれます)。
  • 読み取り専用ファイルを適切に処理します。

コードは次のとおりです(唯一の有用な関数は clear_dir()です):

import os
import stat
import shutil


# http://stackoverflow.com/questions/1889597/deleting-directory-in-python
def _remove_readonly(fn, path_, excinfo):
    # Handle read-only files and directories
    if fn is os.rmdir:
        os.chmod(path_, stat.S_IWRITE)
        os.rmdir(path_)
    elif fn is os.remove:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


def force_remove_file_or_symlink(path_):
    try:
        os.remove(path_)
    except OSError:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


# Code from shutil.rmtree()
def is_regular_dir(path_):
    try:
        mode = os.lstat(path_).st_mode
    except os.error:
        mode = 0
    return stat.S_ISDIR(mode)


def clear_dir(path_):
    if is_regular_dir(path_):
        # Given path is a directory, clear its content
        for name in os.listdir(path_):
            fullpath = os.path.join(path_, name)
            if is_regular_dir(fullpath):
                shutil.rmtree(fullpath, onerror=_remove_readonly)
            else:
                force_remove_file_or_symlink(fullpath)
    else:
        # Given path is a file or a symlink.
        # Raise an exception here to avoid accidentally clearing the content
        # of a symbolic linked directory.
        raise OSError("Cannot call clear_dir() on a symbolic link")
import os
import shutil

# Gather directory contents
contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]

# Iterate and remove each item in the appropriate manner
[os.remove(i) if os.path.isfile(i) or os.path.islink(i) else shutil.rmtree(i) for i in contents]

以前のコメントでは、Python 3.5+でのos.scandirの使用についても言及しています。例:

import os
import shutil

with os.scandir(target_dir) as entries:
    for entry in entries:
        if entry.is_file() or entry.is_symlink():
            os.remove(entry.path)
        elif entry.is_dir():
            shutil.rmtree(entry.path)

このために os.walk()を使用した方がよい場合があります。

os.listdir()はファイルとディレクトリを区別しないため、これらのリンクを解除しようとするとすぐに問題が発生します。 os.walk()を使用して、ディレクトリこちら、および状況に合わせて調整する方法のヒント。

この方法で問題を解決するために使用しました:

import shutil
import os

shutil.rmtree(dirpath)
os.mkdir(dirpath)

古いスレッドだと思いますが、Pythonの公式サイトで何か面白いものを見つけました。ディレクトリ内のすべてのコンテンツを削除する別のアイデアを共有するためだけに。 shutil.rmtree()を使用するときに認証に問題があり、ディレクトリを削除して再作成したくないためです。元のアドレスは http://docs.python.org/2/libraryです。 /os.html#os.walk 。それが誰かを助けることを願っています。

def emptydir(top):
    if(top == '/' or top == "\\"): return
    else:
        for root, dirs, files in os.walk(top, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))

さらに別の解決策:

import sh
sh.rm(sh.glob('/path/to/folder/*'))

* nixシステムを使用している場合、システムコマンドを活用してみませんか?

import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)

この仕事をするための素晴らしい pathlib について誰も言及していないことに驚いています。

ディレクトリ内のファイルのみを削除する場合は、ワンライナーにすることができます

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 

ディレクトリを再帰的に削除するには、次のように記述できます:

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):
    if path.is_file():
        path.unlink()
    elif path.is_dir():
        rmtree(path)

time.sleep()を次の間に追加して、 rmtree makedirs の問題を解決しました:

if os.path.isdir(folder_location):
    shutil.rmtree(folder_location)

time.sleep(.5)

os.makedirs(folder_location, 0o777)

限られた特定の状況に対する回答: サブフォルダーツリーを維持しながらファイルを削除すると仮定すると、再帰アルゴリズムを使用できます。

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        map(recursively_remove_files, [os.path.join(f,fi) for fi in os.listdir(f)])

recursively_remove_files(my_directory)

たぶん少し話題から外れているかもしれませんが、多くの人がそれが便利だと思うと思います

temp_dir を削除すると仮定すると、 os を使用する単一行コマンドは次のようになります。

_ = [os.remove(os.path.join(save_dir,i)) for i in os.listdir(temp_dir)]

注:これは、ファイルを削除するための1行に過ぎません。ディレクトリを削除しません。

これが役立つことを願っています。ありがとう。

以下のメソッドを使用して、ディレクトリ自体ではなくディレクトリの内容を削除します。

import os
import shutil

def remove_contents(path):
    for c in os.listdir(path):
        full_path = os.path.join(path, c)
        if os.path.isfile(full_path):
            os.remove(full_path)
        else:
            shutil.rmtree(full_path)

これを行うだけです。これにより、ディレクトリ内のすべてのファイルとサブディレクトリも削除されます。フォルダー/ディレクトリを損なうことなく。 Ubuntuでエラーなしで正常に動作します。

import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
    for file in files:
        os.remove(os.path.join(root, file))

これは、OSモジュールを使用してリストしてから削除するだけのトリックです!

import os
DIR = os.list('Folder')
for i in range(len(DIR)):
    os.remove('Folder'+chr(92)+i)

私のために働いて、問題があれば知らせてください!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top