How to read a file into a Python list

There are various ways to read a file to a list in Python, I usually use this method to load a list from a file.

This method allows me to specify the file which i want to open, and it allows me to print the found lines in the list.

The code

The .splitlines() function splits the lines when a newline (‘\n’) is found.

lines = []
filetoopen = 'c:/somefolder/fileiwanttoread.csv'
with open(filetoopen) as f:
     lines = f.read().splitlines()
     for line in lines:
         print line

There is another method which I like to use. I use the len(LIST) command to view if the file has been loaded correctly to the list. the len(LIST) command shows the amount of rows which are stored in the list.

You can summon the command by:

print len(lines)
Founder of Cyberwarzone.com.