Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
显示一个1';s和0';二进制格式的Python_Python_String_Image_File_Binary - Fatal编程技术网

显示一个1';s和0';二进制格式的Python

显示一个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

有没有办法从二进制格式中实际获取由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 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)