读取日志文件的Python示例,一行一行地进入列表。
# With '\n', ['1\n', '2\n', '3']
with open('/www/logs/server.log') as f:
content = f.readlines()
# No '\n', ['1', '2', '3']
with open('/www/logs/server.log') as f:
content = f.read().splitlines()
1.读取文件->列表
1.1虚拟日志文件
d:\\server.log
a
b
c
d123
包含1.2 \n
filename = "d:\\server.log"
with open(filename) as f:
lines = f.readlines()print(type(lines))
print(lines)
输出量
<class 'list'>
['a\n', 'b\n', 'c\n', 'd\n', '1\n', '2\n', '3']
1.3 \n
排除在外
filename = "d:\\server.log"
with open(filename) as f: lines = f.read().splitlines()
print(type(lines))
print(lines)
输出量
<class 'list'>
['a', 'b', 'c', 'd', '1', '2', '3']
参考文献:
- Python文档–读写文件
翻译自: https://mkyong.com/python/python-how-to-read-a-file-into-a-list/
推荐阅读--
每周一课 | Python 示例拆分字符串入到字典里面
每日一课 | 如何将String转换为int
每日一课 | Python time.sleep 精准延迟到秒
每日一课 | Python 如何判断一个字符串是否包含另一个字符串?
球分享
球点赞
![62d012a62b30fc19704dc840b6558141.png](https://i-blog.csdnimg.cn/blog_migrate/3b1a3d74a38cb3c177ca1e7d82b279a1.jpeg)
球在看