Python How to read a file into a list?

摘要: Python example to read a log file, line by line into a list.

Python example to read a log file, line by line into a list.

# 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. Read File -> List

1.1 A dummy log file.

d:\\server.log

1.2 \n is included.

filename = "d:\\server.log"
with open(filename) as f:
    lines = f.readlines()
print(type(lines))
print(lines)

Output

<class 'list'>
['a\n', 'b\n', 'c\n', 'd\n', '1\n', '2\n', '3']

1.3 \n is excluded.

filename = "d:\\server.log"
with open(filename) as f:
    lines = f.read().splitlines()
print(type(lines))
print(lines)

Output

<class 'list'>
['a', 'b', 'c', 'd', '1', '2', '3']

References

  1. Python docs – Reading and Writing Files

上一篇: Java How to read a file into a list?
下一篇: Git pull refusing to merge unrelated histories
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号