UnicodeDecodeError:“utf8”编解码器无法解码位置33中的字节0xb1:读取Matlab文件时起始字节无效

2024-06-10 19:30:24 发布

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

我试图找到一个丢失的Matlab脚本,我需要一些数据处理。我写了一些python代码来读取我正在工作的计算机系统上的所有Matlab文件,因为这里有数以千计的Matlab脚本,我对python比Matlab更舒服。当我运行我编写的代码来查找字符串“11rxncmp”,它必须存在于我要查找的脚本中时,我一直得到这个错误。代码如下:

import os
import codecs 

address = 'X:\Data'
fileNames = []   #contains the full file addresses
OneName = []    #contains individual fileNames
fileCorrect = []
#list all folders to iterate through them later on
for subdir, dirs, files in os.walk(address):
    for file in os.listdir(subdir):
        if file.endswith(".m"):
            print(subdir,file)
            fileName = file            
            OneName.append(fileName)
            fileAddress = subdir+'/'+ file
            if 'Retired' in fileAddress:
                continue
            else:
                fileNames.append(fileAddress)
#open and read the files that are stored in fileNames

if len(fileNames) != 0:
    for i in range(len(fileNames)):
        lineNum = 0 
        with codecs.open(fileNames[i],mode = 'r', encoding = 'utf8') as fileOpen:
            for line in iter(fileOpen):
                if 'Retired' in fileOpen.name:                
                    break
                else:            
                    lineNum += 1
                    try:
                        if 'rxnCMP' in line:
                            fileCorrect.append(fileNames[i])
                            print(line)
                            print('Script' + fileNames[i] + ' has this word in it ')
                            print(lineNum)
                            continue 
                        else: 
                            continue 
                    except:
                        break

我得到的错误是:

^{pr2}$

对于行:

for line in iter(fileOpen)

我不知道为什么会这样。可能是因为我正在编写的matlab脚本编码不同吗。在


Tags: 代码in脚本forifoslinefile