从文本文件中删除未知字符

mee*_*eep 2 python windows character-encoding

我有大量文件包含我尝试使用Python脚本处理的数据.

这些文件是未知的编码,如果我在Notepad ++中打开它们,它们包含由加载的"null"字符分隔的数字数据(在Notepad ++中黑色背景上用白色表示为NULL).

为了处理这个问题,我将文件用空字符\ x00分隔,并使用以下脚本仅检索数值:

stripped_data=[]
for root,dirs,files in os.walk(PATH):
    for rawfile in files:
        (dirName, fileName)= os.path.split(rawfile)
        (fileBaseName, fileExtension)=os.path.splitext(fileName)
        h=open(os.path.join(root, rawfile),'r')
        line=h.read()
        for raw_value in line.split('\x00'):
            try:
                test=float(raw_value)
                stripped_data.append(raw_value.strip())
            except ValueError:  
                pass
Run Code Online (Sandbox Code Playgroud)

但是,文件中有时会出现其他无法识别的字符(据我所知,总是在最开始时) - 这些字符在Notepad ++中显示为"EOT","SUB"和"ETX".它们似乎干扰了Python中文件的处理 - 文件似乎以这些字符结束,即使Notepad ++中有明显更多的数据可见.

如何在处理之前从这些文件中删除所有非ASCII字符?

Mar*_*wis 5

您正在以文本模式打开文件.这意味着第一个Ctrl-Z字符被视为文件结束字符.在open()中指定'rb'而不是'r'.