如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
我觉得这个密码起作用了。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
其他回答
我觉得这个密码起作用了。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
注:以防有人对我的答案投了反对票,我在这里有一些事情要解释。
Everyone likes short 'n' simple answers. However, sometimes the reality is not so simple. Back to my answer. I know shutil.rmtree() could be used to delete a directory tree. I've used it many times in my own projects. But you must realize that the directory itself will also be deleted by shutil.rmtree(). While this might be acceptable for some, it's not a valid answer for deleting the contents of a folder (without side effects). I'll show you an example of the side effects. Suppose that you have a directory with customized owner and mode bits, where there are a lot of contents. Then you delete it with shutil.rmtree() and rebuild it with os.mkdir(). And you'll get an empty directory with default (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you're not a superuser). Finally, be patient and read the code. It's long and ugly (in sight), but proven to be reliable and efficient (in use).
这里有一个冗长而丑陋,但可靠而有效的解决方案。
它解决了一些其他答案没有解决的问题:
它正确地处理符号链接,包括不对符号链接调用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")
我必须从一个父目录中的3个独立文件夹中删除文件:
directory
folderA
file1
folderB
file2
folderC
file3
这段简单的代码对我来说很管用:(我用的是Unix)
import os
import glob
folders = glob.glob('./path/to/parentdir/*')
for fo in folders:
file = glob.glob(f'{fo}/*')
for f in file:
os.remove(f)
希望这能有所帮助。
非常直观的方法:
import shutil, os
def remove_folder_contents(path):
shutil.rmtree(path)
os.makedirs(path)
remove_folder_contents('/path/to/folder')
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))