python如何读取文本文件
时间: 2023-03-05 21:23:18 浏览: 50
Python 可以使用内置的 `open` 函数读取文本文件。具体步骤如下:
1. 使用 `open` 函数打开文件,传入文件路径和打开方式(例如 `r` 表示只读方式)作为参数,返回一个文件对象。
```python
file = open("file.txt", "r")
```
2. 使用文件对象的 `read` 方法读取文件内容。`read` 方法默认会读取文件的所有内容,可以传入一个整数参数指定要读取的字节数。返回的是一个字符串。
```python
content = file.read()
```
3. 使用文件对象的 `close` 方法关闭文件。
```python
file.close()
```
完整的代码如下:
```python
file = open("file.txt", "r")
content = file.read()
file.close()
```
在实际使用中,建议使用 `with` 语句来打开文件,这样可以自动关闭文件并且更加安全。例如:
```python
with open("file.txt", "r") as file:
content = file.read()
```
阅读全文
相关推荐


















