python创建txt文件并读写
时间: 2023-08-28 12:26:20 浏览: 88
创建txt文件的代码示例:
```python
# 打开一个文件,如果文件不存在则创建它
file = open("example.txt", "w")
# 向文件中写入内容
file.write("Hello World!\n")
file.write("This is a text file.\n")
# 关闭文件
file.close()
```
读取txt文件的代码示例:
```python
# 打开一个文件
file = open("example.txt", "r")
# 读取文件中的所有内容
content = file.read()
print(content)
# 关闭文件
file.close()
```
向txt文件中追加内容的代码示例:
```python
# 打开一个文件,以追加模式打开
file = open("example.txt", "a")
# 向文件中追加内容
file.write("This is additional content.\n")
# 关闭文件
file.close()
```
阅读全文
相关推荐
![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)
![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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)