1

I have a file.txt which is saving as list

['Joe', '101', '/home/Joe', '43242', '/home/Joe/1.txt']

How to read the last element in the file here it is '/home/Joe/1.txt'

I tried to read

with open ('file.txt', r) as fr:
   fd = fr.readlines()
   print (fd[-1])
aysh
  • 493
  • 1
  • 11
  • 23

3 Answers3

3

You could use ast.literal_eval()

from ast import literal_eval

with open("test.txt") as fp:
    content = fp.read()
    lst = literal_eval(content)
    print(lst[-1])
    # /home/Joe/1.txt

As said in the commentary, better use other structures to store your information, e.g. pickle, json, etc.

Jan
  • 42,290
  • 8
  • 54
  • 79
1

Please change t to 'rt' when reading from a file in python:

with open ('file.txt', 'rt') as fr:
  fd = fr.readlines()
  print (fd[-1])

Note: it is 'rt' instead of t.

0

Try to,

 with open('file.txt') as fr:
     fd = fr.readlines()[0].split(',')[-1].strip(']')
     print(fd)

 #'/home/Joe/1.txt'
Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29