Pythonでファイルやフォルダを削除するには?
os.remove()
ファイルを削除します。
os.rmdir()
空のディレクトリを削除する。
shutil.rmtree()
ディレクトリとその内容をすべて削除する。
Python 3.4+ pathlib
モジュールの Path
オブジェクトもこれらのインスタンスメソッドを公開しています:
pathlib.Path.unlink()
はファイルやシンボリックリンクを削除します。
pathlib.Path.rmdir()
空のディレクトリを削除します。
ファイルを削除するPython構文。 -------------------------------。
import os
os.remove("/tmp/<file_name>.txt")
または。
import os
os.unlink("/tmp/<file_name>.txt")
ベストプラクティス。 --------------。
1。 まず、ファイルまたはフォルダーが存在するかどうかを確認してから、そのファイルを削除するだけです。 これは、
の2つの方法で実現できます。
a。 os.path.isfile( "/ path / to / file")
。
b。 例外処理を使用します。
。
例 os.path.isfile
の場合。
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
。 削除するファイル名を入力します:demo.txt。 エラー:demo.txt-そのようなファイルやディレクトリはありません。削除するファイル名を入力します:rrr.txt。 エラー:rrr.txt-操作は許可されていません。
削除するファイル名を入力:foo.txt。 < / pre>。
Python構文でフォルダを削除します。
shutil.rmtree()
shutil.rmtree()
の例。#!/usr/bin/python import os import sys import shutil # Get directory name mydir= raw_input("Enter directory name: ") ## Try to remove tree; if failed show an error using try...except on screen try: shutil.rmtree(mydir) except OSError as e: print ("Error: %s - %s." % (e.filename, e.strerror))
用途
shutil.rmtree(path[, ignore_errors[, onerror]])
(shutil]1の完全なドキュメントを参照)、および/または
os.remove
と
os.rmdir
(完全なドキュメントは osにあります)。
君たちのために機能を作ろう。
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
Pythonでファイルまたはフォルダを削除するにはどうすればよいですか?
Python 3の場合、ファイルとディレクトリを個別に削除するには、unlink
とrmdir
Path
オブジェクトメソッドをそれぞれ使用します。
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
「Path」オブジェクトで相対パスを使用することもでき、現在の作業ディレクトリを「Path.cwd」で確認することもできます。
Python 2で個々のファイルとディレクトリを削除するには、以下のラベルが付けられたセクションを参照してください。
内容のあるディレクトリを削除するには、shutil.rmtree
を使用し、これはPython 2および3:で利用できることに注意してください。
from shutil import rmtree
rmtree(dir_path)
Python 3.4の新機能は「パス」オブジェクトです。
1つを使用して、使用状況を実証するディレクトリとファイルを作成しましょう。 /
を使用してパスの一部を結合することに注意してください。これは、オペレーティングシステム間の問題とWindowsでのバックスラッシュの使用による問題を回避します( \
のようにバックスラッシュを2倍にするか、または r "foo \ bar"
のような生の文字列):
from pathlib import Path
# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()
file_path = directory_path / 'file'
file_path.touch()
そしていま:
>>> file_path.is_file()
True
次に削除しましょう。 まずファイル:
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
globbingを使用して複数のファイルを削除できます。まず、このためにいくつかのファイルを作成しましょう。
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
次に、グロブパターンを反復します。
>>> for each_file_path in directory_path.glob('*.my'):
... print(f'removing {each_file_path}')
... each_file_path.unlink()
...
removing ~/directory/foo.my
removing ~/directory/bar.my
次に、ディレクトリの削除を示します。
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
ディレクトリとその中のすべてを削除したい場合はどうでしょう? このユースケースには、「shutil.rmtree」を使用します。
ディレクトリとファイルを再作成しましょう:
file_path.parent.mkdir()
file_path.touch()
rmdir
は空でない限り失敗することに注意してください。そのため、rmtreeは非常に便利です。
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/excelsiora/directory'
次に、rmtreeをインポートし、ディレクトリをfuntionに渡します。
from shutil import rmtree
rmtree(directory_path) # remove everything
すべてが削除されたことがわかります。
>>> directory_path.exists()
False
Python 2を使用している場合は、pathlib2と呼ばれるpathlibモジュールのバックポートがあり、pip :でインストールできます。
$ pip install pathlib2
そして、ライブラリを「pathlib」にエイリアスできます。
import pathlib2 as pathlib
または、「Path」オブジェクトを直接インポートします(ここで示されているように)。
from pathlib2 import Path
多すぎる場合は、os.remove
または os.unlink
のファイルを削除できます。
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
または。
unlink(join(expanduser('~'), 'directory/file'))
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
os.removedirs
もあることに注意してください。空のディレクトリを再帰的に削除するだけですが、ユースケースに合う場合があります。
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
os.unlink(path, *, dir_fd=None)
または。
os.remove(path, *, dir_fd=None)
どちらの関数も意味的に同じです。 この関数は、ファイルパスを削除(削除)します。 パスがファイルではなく、ディレクトリの場合、例外が発生します。
shutil.rmtree(path, ignore_errors=False, onerror=None)
または。
os.rmdir(path, *, dir_fd=None)
ディレクトリツリー全体を削除するには、 shutil.rmtree()
を使用できます。 os.rmdir
は、ディレクトリが空で存在する場合にのみ機能します。
os.removedirs(name)
コンテンツのある親まで、selfを持つすべての空の親ディレクトリを削除します。
ex。 os.removedirs( 'abc / xyz / pqr')は、ディレクトリが空の場合、 'abc / xyz / pqr'、 'abc / xyz'、および 'abc'の順序でディレクトリを削除します。
詳細については、公式doc:os.unlink
、[os.remove
](https://docs.python .org / library / os.html#os.remove)、[os.rmdirs
美しく読みやすいコードを書くことがあなたのお茶なら、「サブプロセス」を使用することをお勧めします。
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
また、ソフトウェアエンジニアでない場合は、Jupyterの使用を検討してください。 bashコマンドを入力するだけです。
!rm -r my_dir
伝統的に、あなたは「shutil」を使用します:
import shutil
shutil.rmtree(my_dir)