【问题标题】:I need to read a file bit by bit in python [duplicate]我需要在python中一点一点地读取文件[重复]
【发布时间】:2022-01-04 08:26:24
【问题描述】:

我想从文件中输出类似 01100011010... 或 [False,False,True,True,False,...] 的输出,然后创建加密文件。 我已经尝试过 byte = file.read(1),但我不知道如何将其转换为位。

【问题讨论】:

标签: python file bit


【解决方案1】:

您可以通过这种方式以二进制模式读取文件:

with open(r'path\to\file.ext', 'rb') as binary_file:
    bits = binary_file.read()

'rb' 选项代表Read Binary


对于您要求的输出,您可以执行以下操作:

[print(bit, end='') for bit in bits]

这就是列表推导等价于:

for bit in bits:
    print(bit, end='')

由于'rb'给你的是hex数字而不是bin,你可以使用内置函数bin来解决这个问题:

with open(r'D:\\help\help.txt', 'rb') as file:
    for char in file.read():
        print(bin(char), end='')

【讨论】:

    【解决方案2】:

    假设我们有文本文件text.txt

    # Read the content:
    with open("text.txt") as file:
      content=file.read()
    # using join() + bytearray() + format()
    # Converting String to binary
    res = ''.join(format(i, '08b') for i in bytearray(content, encoding ='utf-8'))
      
    # printing result 
    print("The string after binary conversion : " + str(res))
    

    【讨论】:

    • 读取文件,将其转换为字符串(是的,这就是 file.read() 所做的),然后将其转换为二进制文件效率低下。为什么,您不只是将文件作为二进制文件打开?无论如何,我非常欣赏 res 的内联关联,它真的是 pythonic
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2017-10-08
    • 2013-02-01
    • 2016-03-01
    相关资源
    最近更新 更多