Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

TypeError: can't concat str to bytes (but I'm not using a string) -- Python 3

I have a function that attempts to concatenate a few byte strings:

data.py

def hash_object (data, type_='blob', write=True):
    """ Returns a sha1 hash given bytes data
    :param data: the contents of a file
    :type data: bytes
    :param type_: type of git object
    :type _type: string
    :return oid: a sha1 hash
    :rtype oid: string
    """
    obj = type_.encode() + b"x00" + data # error raised here
    oid = hashlib.sha1(obj).hexdigest()
    if write == True:
        with open (f'{GIT_DIR}/objects/{oid}', 'wb') as out:
            out.write(obj)
    return oid

The data parameter is take from this function in another file meant to handle the cli:

cli.py

def hash_object (args):
    """ hashes a file supplied through args param
    :param args:
    :type args: parser.ArgumentParser
    """
    with open (args.file, 'rb') as f:   # notice this is opening as bytes and feeding it to data module
        print (data.hash_object (f.read ())) 

The error is pointing to this line:

obj = type_.encode() + b"x00" + data 

When I check the types of each argument of +, I can confirm they are bytes. But the error message I get says the following:

>       obj = type_.encode() + b"x00" + data
E       TypeError: can't concat str to bytes

Why does Python think this is str to bytes?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...