打开随机文件时出现UnicodeDecodeError错误?

时间:2018-11-30 17:23:46

标签: python

我正在尝试打开目录中的随机文件并搜索字符串。但是,我得到一个错误。我使用的路径错误还是尝试读取文件的方式错误?

+ (NSLayoutConstraint *) findConstraintNamed:(NSString *)identifierTarget startWith:(UIView *)aView;    
{    
    // walk upward from item through ancestors  
    UIView *currentView = aView;            

    while (currentView != nil)    
    {    
        NSArray *constraints = [currentView constraints];    
        NSInteger foundConstraintIndex = [constraints indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {   
            return [((NSLayoutConstraint *)obj).identifier isEqualToString:identifierTarget];    
        }];


        if (foundConstraintIndex != NSNotFound)    
        {    
            return constraints[foundConstraintIndex];    
        }                

        // not found, so walk up the ancestor chain    
        currentView = currentView.superview;    
    }    

    return nil;  // not found anywhere in item or ancestors!  :(    
}
path = "C:\\Users\\ASDF\\Desktop\\profiles2\\"
random_file = random.choice(os.listdir(path))
filepath = os.path.join(path, random_file)
data = open(filepath).read()
if 'xpression' in data:
    print("true")
     

UnicodeDecodeError:'charmap'编解码器无法解码位置9502上的字节0x9d:字符映射到

1 个答案:

答案 0 :(得分:1)

首先,您提供的代码无法运行;您忘记了一些必要的import语句。

您会收到UnicodeDecodeError,因为Python文本文件的默认编码为UTF-8,如果您从计算机中选择任何随机文件,则该文件可能根本不是UTF-8编码的,甚至根本就没有文本文件用。那时,Unicode UTF8字符解码器无法解码输入。

如果您将编码指定为latin1,则Python假定字节到字符的一对一编码,并且它将不再尝试解码“好像”它是UTF-8。这解决了一个问题。

修复此问题后,在我的随机实验中弹出了另一个:os.listdir不仅返回文件列表,而且还可能包含文件夹。您可以使程序停止并显示相应的错误消息,但也可以在选择文件夹之前将其从列表中删除。这样做有多种方法,例如os.walk,但是我发现了一条神奇的线,可以从How do I list all files of a directory?中提取os.listdir中的文件列表。

以下代码在我的系统上正常运行;多次运行它,有时会说“ true”(诚然,我必须为此更改测试文本;您的原始文本xpression在我自己的文件中出现的频率太低,无法进行测试)

import random,os

path = "."
random_file = random.choice([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
print (random_file)

filepath = os.path.join(path, random_file)

with open(filepath, encoding='latin1') as file:
    data = file.read()
    if 'test' in data:
        print("true")

这可以与设置为latin1的编码一起使用,因为它会这样处理纯ASCII数据,并且不会影响任何二进制内容。但是,如果您的搜索文本包含非ASCII字符(如带重音符号的字母),它将随机失败或成功。 (只有当该随机文件也被编码为Latin-1时,该命令才会成功,但是如果它是UTF-8,则将失败。)