我正在尝试使用奇怪的编码加载文件的列。 Windows 似乎没有问题打开它,但 Linux 提示,我只能使用 Atom 打开它。文本编辑器(其他人要么给我一个空白文件,要么给我一个编码数据的文件)
命令:
file -i data_file.tit
返回:
application/octet-stream; charset=binary
以二进制模式打开文件并读取前 400 个字节给出:
'0905077U1- a\r\n积分时间:19,00 毫秒\r\n平均值:25 次扫描\r\n用于平滑的像素数量:2\r\n使用光谱仪名称测量的数据: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,'
/p>
文件的其余部分仅包含用分号分隔的 ASCII 数字。
我尝试了以下方式来加载文件:
with open('data_file.tit') as f:
bytes = f.read() # (1)
# bytes = f.read().decode('???') # (2)
# bytes = np.genfromtxt(f) # (3)
print bytes
(1)
有点效果,但跳过了前几百行。(2)
每个 encoding 都失败了我尝试了错误:codec can't decode byte 0xb5 in position 315: unexpected special character
(3)
提示ValueError: Some errors were detected !
并为每一行显示类似于Line #3 的内容(有 3 列而不是 2)
。
如何加载这个数据文件?
最佳答案
你有一个 codepage 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'))
那么前 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
NULL 从 用光谱仪名称测量的数据中剥离:0905077U1 行;光谱仪名称现在有 9 个字节长,再加上 55 个 NULL,看起来名称可能长达 64 个字符,文件编写器没有费心去除这些 NULL。
关于python - 读取未知编码的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26122007/