我正在制作一个加密程序,我需要在二进制模式下打开文件来访问非ascii和不可打印字符,我需要检查文件中的字符是字母、数字、符号还是不可打印字符。这意味着我必须检查字节(当它们被解码为ascii时)是否与以下任何字符匹配:
{^9,dzEV=Q4ciT+/s};fnq3BFh% #2!k7>YSU<GyD\I]|OC_e.W0M~ua-jR5lv1wA`@8t*xr'K"[P)&b:g$p(mX6Ho?JNZL
我想我可以把上面的字符编码成二进制,然后用字节来比较。我不知道怎么做。在
^{pr2}$P.S. Sorry for bad English and binary misunderstanding. (I hope you know what I mean by bytes, I mean characters in binary mode like this):
要以二进制模式打开文件,请使用
open("filena.me", "rb")
命令。我从来没有亲自使用过这个命令,但这应该能让你得到你需要的信息。在Python中有两种主要的字符串类型:表示二进制数据的bytestrings(字节序列)和表示人类可读文本的Unicode字符串(Unicode码位序列)。把一个转换成另一个很简单(☯)公司名称:
如果以二进制模式打开文件,例如
^{pr2}$'rb'
,则file.read()
返回bytestring(bytes
类型):有几种方法可用于对字节进行分类:
字符串方法,如
bytes.isdigit()
:字符串常量,如
string.printable
正则表达式,如
\d
curses.ascii
模块中的分类函数,例如curses.ascii.isprint()
bytearray
是一个可变的字节序列-与bytestring不同,您可以就地更改它,例如,每三个大写字节都要小写:注意:
b'ad'
是小写的,但是b'_'
保持不变。在要想就地修改二进制文件,可以使用
mmap
模块,例如,在'file'
中每隔一行将第4列小写:注意:python2和3api在本例中有所不同。代码使用python3。在
输入
输出
注意:第4列在第2行和第4行变为小写。在
通常,如果要更改文件:读取文件,将修改写入临时文件,成功后将临时文件移到原始文件的位置:
输入
输出
要转换回输出,请设置
caesar_shift = -3
。在相关问题 更多 >
编程相关推荐