生成一个读写文件的python代码
时间: 2024-01-14 17:01:55 浏览: 80
下面是一个示例代码,演示了如何使用 Python3 进行文件读写操作:
```python
# 打开文件
file_path = "example.txt"
file = open(file_path, "w")
# 写入文件内容
file.write("Hello, World!\n")
file.write("This is an example file.\n")
# 关闭文件
file.close()
# 打开文件
file = open(file_path, "r")
# 读取文件内容
content = file.read()
# 输出文件内容
print(content)
# 关闭文件
file.close()
```
在这个代码中,首先使用 `open()` 函数打开一个文件,并指定了写入模式(`"w"`)。然后使用 `write()` 方法向文件中写入了两行内容。之后,关闭了文件。
接着,再次使用 `open()` 函数打开文件,并指定了读取模式(`"r"`)。然后使用 `read()` 方法读取了文件中的所有内容,并将其存储在 `content` 变量中。最后,输出文件内容,并关闭文件。
需要注意的是,在实际应用中,需要对文件读写过程中可能出现的异常进行处理,以保证程序的健壮性和稳定性。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)