获取文件解码的最后n行

2024-04-18 01:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个utf-16文件,我正在读最后几行。以下是我现在拥有的:

def get_last_n_lines(self, n, file=None):
    '''
    Sorted from the bottom to the top.
    '''
    file = file or self.file
    s = subprocess.check_output(['tail', '-%s' % str(n), file]).decode('utf-8')
    return

但是,我得到以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 4607: invalid start byte

即使我做了.decode('utf-16'),它也会给我一个错误。从tail命令获取文件最后100行的正确方法是什么?你知道吗


Tags: 文件theselfnonegetdef错误byte
2条回答

有效的方法是在解码方法中添加更通用的unicode编码:

> s = subprocess.check_output(['tail', '-%s' % str(n), file]).decode('unicode_escape')

您可以添加encoding=“437”或encoding=“850”。你知道吗

相关问题 更多 >