-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
  • 119,623
  • 25
  • 170
  • 301
SollyBunny
  • 800
  • 1
  • 8
  • 15

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,896
  • 20
  • 81
  • 137
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.
  • 845
  • 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
  • 69,937
  • 8
  • 61
  • 102
-2

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

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