使用Python忽略二进制文件中的换行符? [英] Ignore newline character in binary file with Python?

查看:445
本文介绍了使用Python忽略二进制文件中的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样打开文件:

f = open("filename.ext", "rb") # ensure binary reading with b

我的第一行数据如下(使用f.readline()时):

My first line of data looks like this (when using f.readline()):

'\x04\x00\x00\x00\x12\x00\x00\x00\x04\x00\x00\x00\xb4\x00\x00\x00\x01\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x18\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00:\x00\x00\x00;\x00\x00\x00<\x00\x00\x007\x00\x00\x008\x00\x00\x009\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n'

问题是,我想逐字节读取此数据(f.read(4)).在调试时,我意识到到第一行的末尾,它仍然接受换行符\n ,并且将其用作我阅读的以下int的第一个字节.我不想简单地使用.splitlines(),因为某些数据内部可能包含n,而且我也不想破坏它.顺便说一下,我正在使用Python 2.7.10.我还读到了使用b参数照顾"新行/行尾字符打开二进制文件的情况.为什么我不这样?

Thing is, I want to read this data byte by byte (f.read(4)). While debugging, I realized that when it gets to the end of the first line, it still takes in the newline character \n and it is used as the first byte of the following int I read. I don't want to simply use .splitlines()because some data could have an n inside and I don't want to corrupt it. I'm using Python 2.7.10, by the way. I also read that opening a binary file with the b parameter "takes care" of the new line/end of line characters; why is not the case with me?

这是在控制台中发生的,因为文件的位置正好在换行符之前:

This is what happens in the console as the file's position is right before the newline character:

>>> d = f.read(4)
>>> d
'\n\x00\x00\x00'
>>> s = struct.unpack("i", d)
>>> s
(10,)

推荐答案

(来自与聊天室中OP的讨论)

(Followed from discussion with OP in chat)

似乎文件是二进制格式,换行符只是误解的值.例如,将10写入文件时,可能会发生这种情况.

Seems like the file is in binary format and the newlines are just mis-interpreted values. This can happen when writing 10 to the file for example.

这并不意味着要换行,并且可能不是.您可以忽略将其打印为\n并将其用作数据.

This doesn't mean that newline was intended, and it is probably not. You can just ignore it being printed as \n and just use it as data.

这篇关于使用Python忽略二进制文件中的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆