Python How to read a file into a list?
By:Roy.LiuLast updated:2019-08-11
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
From:一号门
Previous:Java How to read a file into a list?
COMMENTS