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

  1. Python docs – Reading and Writing Files

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar