Python Paramiko远程文件中的解码错误
我有一个每天自动生成的大型远程文件。我无法控制文件的生成方式。我使用Paramiko打开文件,然后在其中搜索,以确定给定的行是否与文件中的行匹配 但是,我收到以下错误: UnicodeDecodeError:“utf8”编解码器无法解码位置57中的字节0x96:无效的开始字节 我的代码:Python Paramiko远程文件中的解码错误,python,ssh,paramiko,Python,Ssh,Paramiko,我有一个每天自动生成的大型远程文件。我无法控制文件的生成方式。我使用Paramiko打开文件,然后在其中搜索,以确定给定的行是否与文件中的行匹配 但是,我收到以下错误: UnicodeDecodeError:“utf8”编解码器无法解码位置57中的字节0x96:无效的开始字节 我的代码: self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.c
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(host, username=user, password=pass)
self.sftp_client = self.ssh.open_sftp()
self.remote_file = self.sftp_client.open(filepath, mode='r')
def checkPhrase(self, phrase):
found = 0
self.remote_file.seek(0)
for line in self.remote_file:
if phrase in line:
found = 1
break
return found
我在self.remote_文件中的行处收到错误:显然,文件中有一个字符超出了utf8的范围
有没有办法在读取时对行重新编码,或者干脆忽略错误?因此,文件是字节。它们可能有也可能没有特定的编码。此外,因为它忽略了正常打开函数所采用的“b”标志 相反,你应该试着自己解码每一行。首先,以二进制模式打开文件,然后读取一行,然后尝试将该行解码为utf-8。如果失败了,就跳过这一行
def checkPhrase(self, phrase):
self.remote_file.seek(0)
for line in self.remote_file:
try:
decoded_line = line.decode('utf-8') # Decode from bytes to utf-8
except UnicodeDecodeError:
continue # just keep processing other lines in the file, since this one it's utf-8
if phrase in decoded_line:
return True # We found the phrase, so just return a True (instead of 1)
return False # We never found the phrase, so return False (instead of 0)
此外,我还发现Ned Batcheldar在理解字节与unicode的对比方面非常有帮助。因此,文件就是字节。它们可能有也可能没有特定的编码。此外,因为它忽略了正常打开函数所采用的“b”标志 相反,你应该试着自己解码每一行。首先,以二进制模式打开文件,然后读取一行,然后尝试将该行解码为utf-8。如果失败了,就跳过这一行
def checkPhrase(self, phrase):
self.remote_file.seek(0)
for line in self.remote_file:
try:
decoded_line = line.decode('utf-8') # Decode from bytes to utf-8
except UnicodeDecodeError:
continue # just keep processing other lines in the file, since this one it's utf-8
if phrase in decoded_line:
return True # We found the phrase, so just return a True (instead of 1)
return False # We never found the phrase, so return False (instead of 0)
此外,我发现Ned Batcheldar在理解字节与unicode之间的关系方面非常有帮助