如何阅读python

问题描述 投票:0回答:5
有人可以告诉我如何在Python的TXT文件中阅读最后一行的首字母。抱歉,如果问题有点困惑,这是我在堆栈溢出上的第一个问题。

python
5个回答
2
投票
with open('text.txt', 'r') as f: print(list(f)[-1][0])

file_obj = open('myfile.txt')
the_text = file_obj.read()
*_, last_line = text.rsplit('\n', maxsplit=1)
first_char = last_line[0]

1
投票
简单的解决方案来访问文件的最后一行,尽管需要O(n)时间,但正在使用基本循环:

0
投票
file = open("script.txt", "r") last = "" for line in file: last = line print(last[0])

小型文件解决方案。这将打开文件,并通过行迭代,直到文件完全迭代为止。

0
投票
large文件解决方案(也更快)。这利用了

os.seek()
模块。

import os with open('filename.txt', 'rb') as f: f.seek(-2, os.SEEK_END) while f.read(1) != b'\n': f.seek(-2, os.SEEK_CUR) last_line = f.readline().decode() last_line_char = last_line[0]

here

编码

#做到这一点: file = open("thefileyouwantoopen.txt", "r") alllines = file.readlines(); #check for the length of the list displaying all the lines in the file ouch = len(file.readlines()) - 1 #make a variable equal to the last line by calling the last index in the list lastline = file.readline()[ouch] #print the first digit print(lastline[:1])


0
投票

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.