-3

I have a textfile that looks like:

71456137\n
69873481\n
71015205\n
77620788\n
69782796\n
71307244\n
68843955\n
74431739\n
68162271\n
77464886\n
71281027\n
100055063\n
68637778\n
2484\n

I want to read it in in python as a list of strings. I want to ask which is the 4th entry Like:

a = open('mytextfile.txt')
print(a[4])
>>> 69782796

Can someone help me with that?

realr
  • 3,652
  • 6
  • 23
  • 34
Anja
  • 345
  • 5
  • 21

3 Answers3

0

it is possible to insert the strings in the text file in to an array d eliminated with newline character. like below

a = open('mytextfile.txt')
b=a.split('\n')) 
array=[]
for texts in b:
    array=array.add(text)

then you can get your favorite string

fav=array[4]
-1
a = open('mytextfile.txt', 'r').readlines()

another solution:

with open('data.txt', 'r') as a:
    print(a.readlines()[1])
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38
  • 2
    Now you can't use `.close` here. Why not use `with open(...)`. – Ch3steR Mar 11 '20 at 14:33
  • `str.split()` splits on all whitespace characters, not only newlines. Also, files already have a `.readlines()` method, and are iterables too so `list(yourfile)` would work too. – bruno desthuilliers Mar 11 '20 at 14:42
-1
with open('mytextfile.txt') as f:
    a = [line.strip() for line in f.read().split('\\n')]

print(a[4])