【问题标题】:Display a string of 1's and 0's in binary format Python以二进制格式 Python 显示 1 和 0 的字符串
【发布时间】:2012-09-02 22:25:49
【问题描述】:

有什么方法可以从二进制格式中实际获取 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

【问题讨论】:

    标签: python string image file binary


    【解决方案1】:

    这会将字符串中的每个字节转换为 8 个二进制数字,并用空格分隔它们。您可以轻松更改分隔符。

    data = " ".join(bin(ord(b))[2:].rjust(8, "0") for b in data)
    

    【讨论】:

      【解决方案2】:

      使用with,这样您就不必显式关闭 fh

      with open('test.txt','w') as fh:
          fh.write("".join(bin(ord(x))[2:].zfill(8) for x in data)
      

      如果文件很大,上面会占用大量内存,你应该以更小的块读取data并多次调用write()

      旁白:
      fh.close 只是对关闭文件的方法的引用。要调用该方法(即关闭文件),您需要说fh.close()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-30
        • 2015-04-15
        • 2017-07-12
        • 1970-01-01
        • 2019-11-24
        • 2016-01-01
        • 1970-01-01
        相关资源
        最近更新 更多