PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How can I save the content of file as bytes in a variable?

 November 02, 2022     byte, file, python     No comments   

Issue

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 ?


Solution

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'


Answered By - ukBaz
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing