python用shutil删除目录下的文件
时间: 2023-05-11 16:03:04 浏览: 78
可以使用shutil模块中的rmtree函数来删除目录下的所有文件,示例代码如下:
```python
import shutil
# 删除目录下的所有文件
shutil.rmtree('/path/to/directory')
```
注意:该函数会删除目录下的所有文件和子目录,慎用!
相关问题
python 使用shutil 删除指定文件
可以使用以下代码删除指定文件:
```python
import os
import shutil
file_path = "path/to/file"
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} has been deleted.")
else:
print(f"{file_path} does not exist.")
```
请注意,在使用 `shutil` 删除文件时,如果文件不存在会出现 `FileNotFoundError` 错误。因此,最好使用 `os.path.exists()` 函数检查文件是否存在。
python shutil 删除文件
以下是使用shutil模块删除文件的两个示例:
示例1:删除指定目录下的文件夹及其内容
```python
import shutil
import os
location = "E:/Projects/PythonPool/"
dir = "Test"
path = os.path.join(location, dir)
shutil.rmtree(path)
```
示例2:删除指定目录下的文件夹及其内容
```python
import shutil
import os
# location
location = "E:/Projects/PythonPool/"
# directory
dir = "Test"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
```