如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
我觉得这个密码起作用了。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
其他回答
使用操作系统。Python 3.6+中的scandir和上下文管理器协议:
import os
import shutil
with os.scandir(target_dir) as entries:
for entry in entries:
if entry.is_dir() and not entry.is_symlink():
shutil.rmtree(entry.path)
else:
os.remove(entry.path)
Python的早期版本:
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
[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents]
扩展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))
非常直观的方法:
import shutil, os
def remove_folder_contents(path):
shutil.rmtree(path)
os.makedirs(path)
remove_folder_contents('/path/to/folder')
我觉得这个密码起作用了。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
对此,最好使用os.walk()。
Os.listdir()并不区分文件和目录,你很快就会遇到麻烦,试图解除这些链接。这里有一个使用os.walk()递归删除目录的好例子,并提示了如何使其适应您的环境。