python怎么从文本中读取信息
时间: 2023-06-18 21:07:09 浏览: 45
你可以使用Python自带的`open()`函数来打开文本文件,然后使用`.read()`或`.readlines()`方法来读取文件中的内容。
例如,假设你有一个名为`example.txt`的文本文件,它包含以下内容:
```
Hello World!
This is an example file.
```
你可以使用以下代码来读取文件内容:
```python
with open('example.txt', 'r') as f:
content = f.read()
print(content)
```
输出结果为:
```
Hello World!
This is an example file.
```
如果你想一次读取一行内容,可以使用`.readline()`方法:
```python
with open('example.txt', 'r') as f:
line = f.readline()
while line:
print(line)
line = f.readline()
```
输出结果为:
```
Hello World!
This is an example file.
```