显示一个1';s和0';二进制格式的Python
有没有办法从二进制格式中实际获取由1和0组成的字符串显示一个1';s和0';二进制格式的Python,python,string,image,file,binary,Python,String,Image,File,Binary,有没有办法从二进制格式中实际获取由1和0组成的字符串 # read in image data fh = open('test.png','rb') data = fh.read() fh.close() # write binary to text file fh = open('test.txt','w') fh.write(data) fh.close fh.close() 如何将该数据字符串转换为1和0,以便不必显式关闭fh with open('test.txt','w') as
# read in image data
fh = open('test.png','rb')
data = fh.read()
fh.close()
# write binary to text file
fh = open('test.txt','w')
fh.write(data)
fh.close
fh.close()
如何将该数据字符串转换为1和0,以便不必显式关闭fh
with open('test.txt','w') as fh:
fh.write("".join(bin(ord(x))[2:].zfill(8) for x in data)
如果文件较大,则上述操作将占用大量内存,相反,您应该以较小的块读取数据
,并多次调用write()
旁白:fh.close
只是对关闭文件的方法的引用。要调用该方法(即关闭文件),您需要说fh.close()
,这将把字符串中的每个字节转换为8个二进制数字,并用空格分隔。您可以轻松地更改分隔符
data = " ".join(bin(ord(b))[2:].rjust(8, "0") for b in data)