-1

I have a notepad text file with a list of names

eg.

raymond james  
warren buffett  
ernest giles  
william blair  

How would I turn this into a list where each list item is the WHOLE name on each line.
So my list would be:

['raymond james', 'warren buffet', 'ernest giles', 'william blair']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
MeHead
  • 7
  • 1
  • 1
  • 5
  • Use `readlines` Ex: `with open(filename) as infile: result = infile.readlines()` – Rakesh Aug 20 '18 at 15:23
  • If it is a single string, just use `those_lines.splitlines()` If it is in a file, use `.readlines()` – dawg Aug 20 '18 at 15:23
  • @dawg, `.readlines()` leaves trailing newlines, so `.read().splitlines()` should rather be used. – taras Aug 20 '18 at 15:33
  • Possible duplicate of [In Python, how do I read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/in-python-how-do-i-read-a-file-line-by-line-into-a-list) – jpmc26 Aug 20 '18 at 19:58

3 Answers3

5

Simply open the file in read mode, and use the readlines() method:

with open('your_file.txt', 'r') as myfile:

    lines = myfile.readlines()

And you can use a simple list comprehension to remove the newline characters (\n):

lines = [i.strip() for i in lines]
rahlf23
  • 8,869
  • 4
  • 24
  • 54
2

I suggest you to use strip() to avoid newline characters and trailing whitespaces. There is no need of readlines() in this case:

with open('file.txt', 'r') as f:
    lines = [line.strip() for line in f]

print(lines)  # ['raymond james', 'warren buffet', 'ernest giles', 'william blair']

Or if you don't like list comprehension, you can also use map() as follows:

with open('file.txt', 'r') as f:
    lines = list(map(str.strip,f))

print(lines)
Laurent H.
  • 6,316
  • 1
  • 18
  • 40
2

In Python, files opened as text are iterable over their lines. The simplest solution is therefore

with open('myfile.txt') as f:
     my_list = list(f)

This is better than using readlines because the iterator strips newlines while readlines does not.

If you want to strip additional spaces from each line, as other answers suggest, you can use a comprehension:

with open('myfile.txt') as f:
     my_list = [line.strip() for line in f]

or map:

with open('myfile.txt') as f:
     my_list = list(map(str.strip, f))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264