Python – How to read a file 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
a
b
c
d
1
2
3
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
About Author
Comments
Subscribe
0 Comments