python 使用shutil 删除指定文件
时间: 2024-05-14 10:13:38 浏览: 25
可以使用以下代码删除指定文件:
```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)
```
python 删除指定文件
在 Python 中,你可以使用 `os.remove()` 函数来删除指定的文件。下面是示例代码:
```python
import os
# 删除指定文件
os.remove("path/to/file")
```
请将 `"path/to/file"` 替换为要删除的文件的实际路径。请注意,一旦文件被删除,它将无法恢复,所以在删除文件之前请确保你真的打算删除它。如果你想删除一个目录及其内部的所有文件和子目录,可以使用 `shutil.rmtree()` 函数。例如:
```python
import shutil
# 删除目录及其内部的所有文件和子目录
shutil.rmtree("path/to/directory")
```
请将 `"path/to/directory"` 替换为要删除的目录的实际路径。与删除文件一样,请谨慎使用此操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)