python - 获取文件的最后 n 行 -- 解码错误
问题描述
我有一个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”编解码器无法解码位置 4607 中的字节 0xae:无效的起始字节
即使我这样做.decode('utf-16')
,它也会给我一个错误。从 tail 命令获取文件最后 100 行的正确方法是什么?
解决方案
起作用的是在 decode 方法中添加更通用的 unicode 编码:
> s = subprocess.check_output(['tail', '-%s' % str(n), file]).decode('unicode_escape')
推荐阅读
- swift - 无法从核心位置回调请求指南针校准
- android - 打开一个对话框来安装应用程序而不是 Playstore
- c# - 如何取消使用 Continuewith 的任务?
- android - Recyclerview 不更新数据列表
- tomcat - tomcat请求转发被禁止
- r - 如何修改函数中的参数?
- keras - 我可以在 Keras Dense Layer 上使用 3D 输入吗?
- reactjs - 使用反应调用 MVC 端点时 Map() 不是函数
- python - 使用无服务器离线启动调试 python 应用程序时出现 Pdb 错误
- unix - 为固定宽度文件计算 Unix 中只有空格的字符串长度