我正在逐行读取Python中的文件,我需要知道在读取时哪一行是最后一行,如下所示:
f = open("myfile.txt")
for line in f:
if line is lastline:
#do smth
Run Code Online (Sandbox Code Playgroud)
从我发现的例子中我发现它涉及搜索和完整的文件读数以计算行数等.我可以检测到当前行是最后一行吗?我试图检查"\n"是否存在,但在很多情况下,最后一行后面没有反斜杠N.
对不起,如果我的问题是多余的,因为我没有在SO上找到答案
检查is最后一行是否排成一行:
with open("in.txt") as f:
lines = f.readlines()
last = lines[-1]
for line in lines:
if line is last:
print id(line),id(last)
# do work on lst line
else:
# work on other lines
Run Code Online (Sandbox Code Playgroud)
如果你想要第二行使用 last = lines[-2]
或者干脆:
with open("in.txt") as f:
lines = f.readlines()
last = lines[-1]
for line in lines[:-1]:
# work on all but last line
# work on last
Run Code Online (Sandbox Code Playgroud)
import os
path = 'myfile.txt'
size = os.path.getsize(path)
with open(path) as f:
for line in f:
size -= len(line)
if not size:
print('this is the last line')
print(line)
Run Code Online (Sandbox Code Playgroud)
secondLastLine = None
lastLine = None
with open("myfile.txt") as infile:
secondLastLine, lastLine = infile.readline(), infile.readline()
for line in infile:
# do stuff
secondLastLine = lastLine
lastLine = line
# do stuff with secondLastLine
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17094 次 |
| 最近记录: |