23

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]
Kian
  • 1,319
  • 1
  • 13
  • 23
kidkd
  • 239
  • 1
  • 2
  • 3

7 Answers7

55

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]
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    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 Jun 29 '10 at 15:18
  • 5
    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 Jun 29 '10 at 15:24
  • @Fred: Good idea, if you want to write it as answer, I will remove it from mine. – Felix Kling Jun 29 '10 at 15:26
  • @Felix Kling: Thanks. Let's just call it a collaborative effort. 8v) – Fred Larson Jun 29 '10 at 15:29
  • Using the answer [here](http://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines), you can do all this in one line: `myNames = file('names.txt').read().splitlines()` – Hamman Samuel Jan 31 '16 at 14:15
12
f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?
Robus
  • 8,067
  • 5
  • 47
  • 67
9
names=[line.strip() for line in open('names.txt')]
dugres
  • 12,613
  • 8
  • 46
  • 51
2
#function call
read_names(names.txt)
#function def
def read_names(filename): 
with open(filename, 'r') as fileopen:
    name_list = [line.strip() for line in fileopen]
    print (name_list)
1

This should be a good case for map and lambda

with open ('names.txt','r') as f :
   Names = map (lambda x : x.strip(),f_in.readlines())

I stand corrected (or at least improved). List comprehensions is even more elegant

with open ('names.txt','r') as f :
    Names = [name.rstrip() for name in f]
peterb
  • 891
  • 8
  • 7
1

The pythonic way to read a file and put every lines in a list:

from __future__ import with_statement #for python 2.5
Names = []
with open('C:/path/txtfile.txt', 'r') as f:
    lines = f.readlines()
    Names.append(lines.strip())
Kian
  • 1,319
  • 1
  • 13
  • 23
0
Names = []
for line in open('names.txt','r').readlines():
    Names.append(line.strip())

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

Lauro Oliveira
  • 2,362
  • 1
  • 18
  • 12