-2

I already know how to get a text file into python but...I now want to turn that file into a list.

My file:

1
2
3

My code:

file = open("File.txt", "r")
file = list(file)

Is there a way to actually make it into something that works? And if you find an answer please make it simple.

martineau
  • 112,593
  • 23
  • 157
  • 280
SollyBunny
  • 535
  • 1
  • 5
  • 12

4 Answers4

1

EDIT My final solution. Thanks to @juanpa.arrivillaga for the hint that the intermediate iterator-operation is not necessary

map(str.strip, open('asd.txt'))

Or if you like it more, then this:

[x.strip() for x in open('File.txt')]
tim
  • 9,505
  • 17
  • 74
  • 133
0
$ echo -e "one\ntwo\nthree" > /tmp/list.txt
$ cat /tmp/list.txt 
one
two
three
$ python -c "fh = open('/tmp/list.txt'); print(fh.readlines())"
['one\n', 'two\n', 'three\n']
Kenneth D.
  • 825
  • 3
  • 10
  • 18
  • 1
    Not sure the shell is necessary just to answer `readlines()`... – OneCricketeer May 03 '17 at 17:30
  • true, it seemed simplest for creating the txt file used in the example as well, but you are right, it adds an unnecessary abstraction SollyBunny may not be familiar with – Kenneth D. May 03 '17 at 17:36
0

Try this:

f = open('filename.txt').readlines()
f = [int(i.strip('\n')) for i in f]

print(f)
Ajax1234
  • 66,333
  • 7
  • 57
  • 95
-2

you could use numpy's loadtxt if your entries are numbers

import numpy as np
data = np.loadtxt('test.txt')
Simon Hobbs
  • 930
  • 7
  • 11