简体   繁体   English

在python上尾巴 最佳性能实施

[英]Tail on python. Best performance implementation

I'm newbie to programming and in Python as well. 我是编程和Python的新手。
I wrote a function that implements the unix's tail: 我写了一个实现unix尾巴的函数:

def tail(file):
    strin = open(file, 'r')
    lis = strin.readlines()
    lastline = lis[-1]
    return lastline
    strin.close()

But I think that it is not optimal in performance. 但是我认为它并不是最佳的性能。
How can I improve? 我该如何改善?

You can use this Recipe from Collections.deque 您可以从Collections.deque使用此食谱

def tail(filename, n=10):
    'Return the last n lines of a file'
    return deque(open(filename), n)

Refer this :- https://docs.python.org/2/library/collections.html#deque-recipes 请参阅: -https : //docs.python.org/2/library/collections.html#deque-recipes

There's no need to store all the lines since you only want the last one: 不需要存储所有行,因为您只需要最后一行:

lis = strin.readlines()
lastline = lis[-1]

More efficient is as per the answers to Iterate through Python list and do something on last element : 根据对Python列表进行迭代并在最后一个元素上执行操作的答案,效率更高:

for line in open(file, 'r'):
    pass
else:
    return line

(I was not aware of the Collections.deque solution and I agree it's better, also parameterizable for n lines) (我不知道Collections.deque解决方案,我同意它更好,也可以对n行进行参数化)

There are a couple of problems with your code. 您的代码有两个问题。 First you are closing the file after the return. 首先,您要在返回后关闭文件。 Everything after the return statement will not be reached. return语句之后的所有内容都不会到达。 Second, when you're working with files, you should use with . 其次,当你使用文件时,应使用with It opens your file, and when it leaves the block it will close it for you. 它将打开您的文件,当它离开块时,它将为您关闭文件。 And at last, you can merge three lines to an oneliner. 最后,您可以将三行合并为一个单行。

I would wrote it like this: 我会这样写:

def tail(file):
    with open(file, 'r') as o:
        return o.readlines()[-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM