I am using Python 3.6.1. This program simply allows a user to enter some bytes as a "string" and it writes those bytes to a file as actual bytes in the order provided.

import sys

WELCOME_MSG = ("Welcome to Byte Writer. Enter some bytes separated by spaces "
            "like 49 A7 9F 4B when prompted. 'exit' or 'quit' to leave")
FILE_WRITE_ERROR = "Error writing to file... exiting."
INVALID_INPUT_ERROR = ("Improper byte format. Remember to enter "
    "2 chars at a time separated by spaces. Hex digits only")
INPUT_PROMPT = "Enter bytes: "
VALID_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']

def main(argv):
    if not validate_args(argv):
        return -1
    with open(argv[1], "ab") as f:
        while run_loop(argv, f) is True:

    print("Have a nice day.")

def run_loop(argv, f):
    output_list = []
    ui = input(INPUT_PROMPT)
    if ui == "exit" or ui == "quit":
        return False

    list_of_str_bytes = ui.split(' ')
    if validate_input_list(list_of_str_bytes) is False:
        return False

    for b in list_of_str_bytes:
        output_list.append( int(b, 16) )

        return False
    return True

def validate_args(argv):
    if len(argv) != 2:
        print("USAGE: {} [filename to save to]".format(argv[0]))
        return False
    return True

def validate_input_list(input_list):
    for b in input_list:
        if len(b) != 2 or not valid_chars(b):
            return False

    return True

def valid_chars(chars):
    for c in chars:
        if c not in VALID_CHARS:
            return False

        return True
if __name__ == '__main__':
  • 1
    \$\begingroup\$ It looks like the indentation in your function valid_chars is off. I guess the final return should be one level further out, otherwise you only ever check the first character. \$\endgroup\$
    – Graipher
    May 14, 2019 at 9:03

1 Answer 1


Consider using any() for implementing validate_input_list and valid_chars


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.