Home > Mobile >  How can I save the content of file as bytes in a variable?
How can I save the content of file as bytes in a variable?

Time:10-27

Given a text file, for example: a.txt , that his max-size is 16 bytes and it contains some text. How can I read all the content of this file (all the bytes of this file) and save it in variable without to open this file?
Namely, I don't want to do open("a.txt", "r").read() , but, I looking for something like:

a = bytes(`cat file.txt`)

In style of linux.
Can I do it in python ?

CodePudding user response:

Reading bytes from a file and storing it in a variable can be done with my_var = Path('a.txt').read_bytes()

bytes has rjust and ljust to pad using the specified fill byte.

These can be combined to always give a result 16 bytes in length. e.g.

Path('a.txt').read_bytes().rjust(16, b'x')

Here is a fuller example of using this:

from pathlib import Path


small_test = Path.home().joinpath('sml_test.txt')
big_test = Path.home().joinpath('big_test.txt')
small_payload = b'12345678'
full_payload = b'0123456789ABCDEF'


def write_test_files():
    small_test.write_bytes(small_payload)
    big_test.write_bytes(full_payload)


def read_test_files():
    data1 = small_test.read_bytes().rjust(16, b'x')
    data2 = big_test.read_bytes().rjust(16, b'x')
    print(f"{data1 = }")
    print(f"{data2 = }")


def main():
    write_test_files()
    read_test_files()
    small_test.unlink()
    big_test.unlink()


if __name__ == '__main__':
    main()

Which gave the following output:

data1 = b'xxxxxxxx12345678'
data2 = b'0123456789ABCDEF'
  • Related