python读取txt文件
时间: 2023-06-23 22:01:44 浏览: 179
好的,我可以为您提供一些关于Python读取txt文件的基本知识。
在Python中,可以使用open()函数来读取txt文件。下面是一个简单的示例代码:
```python
with open('example.txt', 'r') as f:
content = f.read()
print(content)
```
其中,'example.txt'是要读取的文件名,'r'表示以只读模式打开文件。with语句可以自动关闭文件。read()方法可以读取整个文件的内容并返回一个字符串。
如果您需要逐行读取文件,可以使用readlines()方法,如下所示:
```python
with open('example.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
```
这将逐行读取文件中的内容,并将每行作为一个字符串存储在列表中。然后,可以使用for循环打印每行内容。
希望这些信息对您有所帮助!
阅读全文
相关推荐
















