-
Notifications
You must be signed in to change notification settings - Fork 312
/
getFileLastLine.py
79 lines (71 loc) · 2.25 KB
/
getFileLastLine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:get-last-line-of-file.py
User: Guodong
Create Date: 2016/9/1
Create Time: 11:05
"""
import os
# Refer: http://www.pythonclub.org/python-files/last-line
def get_last_line(path):
file_size = os.path.getsize(path)
block_size = 1024
dat_file = open(path, 'rb')
last_line = ""
if file_size > block_size:
max_seek_point = (file_size // block_size)
dat_file.seek((max_seek_point - 1) * block_size)
elif file_size:
# max_seek_point = block_size % file_size
dat_file.seek(0, 0)
lines = dat_file.readlines()
if lines:
last_line = lines[-1].strip()
# print "last line : ", last_line
dat_file.close()
return last_line
# Refer: http://code.activestate.com/recipes/578095/
def print_first_last_line(path):
file_size = os.path.getsize(path)
block_size = 1024
dat_file = open(path, 'rb')
headers = dat_file.readline().strip()
if file_size > block_size:
max_seek_point = (file_size // block_size)
dat_file.seek(max_seek_point * block_size)
elif file_size:
max_seek_point = block_size % file_size
dat_file.seek(max_seek_point)
lines = dat_file.readlines()
last_line = ""
if lines:
last_line = lines[-1].strip()
# print "first line : ", headers
# print "last line : ", last_line
return headers, last_line
# My Implementation
def get_file_last_line(path):
file_size = os.path.getsize(path)
block_size = 1024
with open(path, 'rb') as f:
last_line = ""
if file_size > block_size:
max_seek_point = (file_size // block_size)
f.seek((max_seek_point - 1) * block_size)
elif file_size:
f.seek(0, 0)
lines = f.readlines()
if lines:
lineno = 1
while last_line == "":
last_line = lines[-lineno].strip()
lineno += 1
return last_line
if __name__ == '__main__':
# Test purpose
print(get_last_line(os.path.abspath(__file__)))
print(print_first_last_line(os.path.abspath(__file__)))
print(get_file_last_line(os.path.abspath(__file__)))