python增删文件
时间: 2024-10-26 20:03:33 浏览: 20
在Python中,操作文件通常涉及到`os`和`shutil`两个内置模块。如果你想增加或删除文件,可以使用以下方法:
**添加文件**:
1. 使用`open()`函数打开文件,并可以选择`a`模式(追加)来在文件末尾添加内容:
```python
with open('filename.txt', 'a') as file:
file.write('\nNew content to add.')
```
2. 如果需要一次性写入大量数据,可以使用`writelines()`方法:
```python
lines = ['Line 1', 'Line 2']
with open('filename.txt', 'w') as file:
file.writelines(lines)
```
**删除文件**:
1. 使用`os.remove()`方法直接删除已存在的文件:
```python
import os
if os.path.exists('filename.txt'):
os.remove('filename.txt')
```
2. 如果文件夹中有文件需要递归删除,可以使用`shutil.rmtree()`:
```python
import shutil
shutil.rmtree('foldername', ignore_errors=True) # 请注意ignore_errors=True忽略错误,以防意外
```
记得处理可能出现的异常,如文件不存在等。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)