How do you read a file into a list in Python?

user474713 picture user474713 · Oct 13, 2010 · Viewed 583.1k times · Source

I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.

I've tried using open but it gives me invalid syntax (the file name I chose was "numbers" and it saved into "My Documents" automatically, so I tried open(numbers, 'r') and open(C:\name\MyDocuments\numbers, 'r') and neither one worked).

Answer

Corey Goldberg picture Corey Goldberg · Oct 13, 2010
with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()

this will give you a list of values (strings) you had in your file, with newlines stripped.

also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.