python删除txt文档
时间: 2024-01-26 22:04:02 浏览: 26
删除txt文档可以使用Python中的os模块。以下是一个示例代码,可以删除指定路径下的txt文档:
```python
import os
path = 'C:/Users/user/Desktop/' # 指定路径
file_list = os.listdir(path) # 获取路径下所有文件
for file in file_list:
if file.endswith('.txt'): # 判断是否为txt文档
os.remove(os.path.join(path, file)) # 删除txt文档
```
在上述代码中,首先指定了需要删除txt文档的路径,然后使用os模块的listdir函数获取路径下所有的文件。接着使用for循环遍历文件列表,判断文件是否为txt文档,如果是,就使用os模块的remove函数删除该文档。最后,所有的txt文档都会被删除。
相关问题
Python删除txt文件
在Python中,你可以使用`os`模块来删除txt文件。具体的步骤如下:
1. 首先,导入`os`模块:`import os`
2. 使用`os.remove()`函数来删除文件,传入要删除的文件路径作为参数。例如,如果要删除名为`example.txt`的文件,可以使用以下代码:`os.remove("example.txt")`
请注意,删除文件是一个不可逆的操作,请确保你真的想要删除该文件。另外,如果文件不存在,将会引发`FileNotFoundError`异常。
使用python删除txt文档
可以使用Python的os模块中的remove函数来删除txt文档,具体代码如下:
```python
import os
file_path = "example.txt" # 文件路径
if os.path.exists(file_path): # 判断文件是否存在
os.remove(file_path) # 删除文件
print("文件删除成功")
else:
print("文件不存在")
```
其中,file_path是要删除的txt文档的路径。首先使用os.path.exists()函数判断文件是否存在,如果存在,则使用os.remove()函数删除该文件;如果不存在,则输出提示信息"文件不存在"。
相关推荐
![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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)