tags:

views:

71

answers:

4

Say I have an empty list myNames = []

How can I open a file with names on each line and read in each name into the list?

like

names.txt
dave
jeff
ted
myNames = [dave,jeff,ted]
+6  A: 

Read the documentation:

with open('names.txt', 'r') as f:
    myNames = f.readlines()

The others already provided answers how to get rid of the newline character.

Update:

Fred Larson provides a nice solution in his comment:

with open('names.txt', 'r') as f:
    myNames = [line.strip() for line in f]
Felix Kling
change `open(file, 'r')` to `open('names.txt', 'r')`. `file` is a build-in type which shouldn't be used as variable name either... Otherwise, good solution.
tux21b
@tux21b: You are right, thank you.
Felix Kling
If we wanted to incorporate the `strip` into this solution, I'd probably do it like so: `myNames = [line.strip() for line in f]`.
Fred Larson
+1 for linking to documentation.
mizipzor
@Fred: Good idea, if you want to write it as answer, I will remove it from mine.
Felix Kling
@Felix Kling: Thanks. Let's just call it a collaborative effort. 8v)
Fred Larson
+3  A: 
f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?
Robus
A: 
Names = []
for line in open('names.txt','r').readlines():
    Names.append(line.strip())

strip() cut spaces in before and after string...

olarva
You are iterating two times over the file content...
Felix Kling
+2  A: 
names=[line.strip() for line in open('names.txt')]
dugres