python文件操作案例
时间: 2023-11-01 18:55:58 浏览: 104
Python文件操作有多种案例,以下是其中的一些例子:
1. 打开和关闭文件:
```python
file = open("filename.txt", "r") # 以只读模式打开文件
content = file.read() # 读取文件内容
file.close() # 关闭文件
```
2. 读取文件内容:
```python
with open("filename.txt", "r") as file:
content = file.read()
print(content)
```
3. 写入文件内容:
```python
with open("filename.txt", "w") as file:
file.write("Hello, world!")
```
4. 创建新文件:
```python
file = open("newfile.txt", "w")
file.close()
```
5. 删除文件:
```python
import os
os.remove("filename.txt")
```
6. 重命名文件:
```python
import os
os.rename("oldfile.txt", "newfile.txt")
```
7. 复制文件:
```python
import shutil
shutil.copyfile("source.txt", "destination.txt")
```
8. 移动文件:
```python
import shutil
shutil.move("source.txt", "destination.txt")
```
这些案例只是Python文件操作的一小部分,你可以根据你的具体需求进行进一步学习和探索。如果你想了解更多关于Python文件操作的案例和技巧,可以参考Python官方文档或者其他Python编程书籍。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)