python txt文件读写
时间: 2024-11-20 14:29:09 浏览: 25
Python提供了许多方法来读写文本文件。以下是一些基本的示例:
**读取文本文件**
你可以使用Python的内置函数`open()`打开一个文本文件,并使用`read()`方法读取文件内容。
```python
# 打开文件
file = open("example.txt", "r")
# 读取文件内容
content = file.read()
# 关闭文件
file.close()
# 输出文件内容
print(content)
```
**写入文本文件**
你可以使用Python的内置函数`open()`打开一个文本文件,并使用`write()`方法写入内容。
```python
# 打开文件以写入
file = open("example.txt", "w")
# 写入内容
file.write("Hello, World!")
# 关闭文件
file.close()
```
如果你要写入多行文本,可以使用`writelines()`方法。
```python
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
# 打开文件以写入多行文本
file = open("example.txt", "w")
# 写入多行文本
file.writelines(lines)
# 关闭文件
file.close()
```
请注意,当你使用`open()`函数打开文件时,第二个参数指定了文件的打开模式。在上述示例中,我们使用了"r"模式来读取文件,和"w"模式来写入文件。其他常见的模式包括"a"用于追加模式,以及"b"用于二进制模式(对于非文本文件类型)。你也可以在模式字符串中包含多个模式。例如,你可以同时使用读取和写入模式打开文件,如下:`open("example.txt", "r+")`。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)