如何读取文件中的最后一个字符串

时间:2020-05-22 11:35:18

标签: python

我有一个file.txt文件,该文件另存为列表

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

如何读取文件中的最后一个元素,这里是'/home/Joe/1.txt'

我尝试阅读

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

3 个答案:

答案 0 :(得分:3)

您可以使用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

如评论中所述,最好使用其他结构来存储您的信息,例如picklejson

答案 1 :(得分:1)

从python中读取文件时,请将 t更改为“ rt”

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

注意:它是 'rt' ,而不是 t

答案 2 :(得分:0)

尝试,

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

 #'/home/Joe/1.txt'