读取编码未知的文件

Gab*_*iel 2 python file-io encoding file character-encoding

我正在尝试使用奇怪的编码加载文件的列。Windows似乎没有问题可以打开它,但是Linux抱怨,我只能使用Atom文本编辑器来打开它(其他人给我的是空白文件或带有编码数据的文件)

命令:

file -i data_file.tit
Run Code Online (Sandbox Code Playgroud)

返回:

application/octet-stream; charset=binary
Run Code Online (Sandbox Code Playgroud)

以二进制模式打开文件并读取前400个字节可得到:

'0905077U1- a\r\nIntegration time: 19,00 ms\r\nAverage: 25 scans\r\nNr of pixels used for smoothing: 2\r\nData measured with spectrometer name: 0905077U1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\r\nWave ;Dark ;Ref ;Sample ;Absolute Irradiance ;Photon Counts\r\n[nm] ;[counts] ;[counts] ;[counts] ;[\xb5Watt/cm\xb2/nm] ;[\xb5Mol/s/m\xb2/nm]\r\n247,40;-1,0378;18,713;10,738;21,132;0,4369\r\n247,'

文件的其余部分仅由分号分隔的ASCII码组成。

我尝试了以下方式来加载文件:

with open('data_file.tit') as f:
    bytes = f.read() # (1)
    # bytes = f.read().decode('???')  # (2)
    # bytes = np.genfromtxt(f)  # (3)
    print bytes
Run Code Online (Sandbox Code Playgroud)
  • (1) 有点工作,但跳过了前几百行。

  • (2)我尝试使用该错误进行的每种编码均失败:

    codec can't decode byte 0xb5 in position 315: unexpected special character
    
    Run Code Online (Sandbox Code Playgroud)
  • (3)ValueError: Some errors were detected !对每一行进行投诉并显示与相似的内容Line #3 (got 3 columns instead of 2)

如何加载该数据文件?

oji*_*jii 5

猜测编码可能真的很困难,幸运的是,有一个库可以尝试提供帮助:https : //pypi.python.org/pypi/chardet


Mar*_*ers 5

您有一个代码页 1252编码的文本文件,其中一行包含 NULL 字节。该file命令根据这些 NULL 确定您有二进制数据,而我根据代表和字符的\xb2\xb5代码点进行了有根据的猜测。²µ

要打开,只需从该编码解码:

import io

with io.open(filename, 'r', encoding='cp1252') as f:
    for line in f:
        print(line.rstrip('\n\x00'))
Run Code Online (Sandbox Code Playgroud)

前 10 行是:

0905077U1- a
Integration time: 19,00 ms
Average: 25 scans
Nr of pixels used for smoothing: 2
Data measured with spectrometer name: 0905077U1
Wave   ;Dark     ;Ref      ;Sample   ;Absolute Irradiance  ;Photon Counts
[nm]   ;[counts] ;[counts] ;[counts] ;[µWatt/cm²/nm]       ;[µMol/s/m²/nm]
247,40;-1,0378;18,713;10,738;21,132;0,4369
247,57;3,0793;19,702;9,5951;11,105;0,2298
247,74;-0,9414;19,929;8,8908;16,567;0,3430
Run Code Online (Sandbox Code Playgroud)

使用光谱仪名称测量数据中去除 NULL :0905077U1行;光谱仪名称现在有 9 个字节长,加上 55 个 NULL,看起来该名称最长可达 64 个字符,并且文件编写者没有费心去除这些 NULL。