Search code examples
pythonpython-unicode

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 2: invalid start byte | Decoding File Size | Python


I tried file encryption method using Crypto Library. But have a problem with receiving side try to decode file size. This is my code

Sender Code

client.send('file.txt'.encode())
client.send(str(file_size).encode())
client.sendall(encrypted)
client.send(b'<END>')
client.close()

Receiver Code

file_name = client.recv(1024).decode()
print(file_name)
file_size = client.recv(1024).decode()
print(file_size)

I tried file_size = client.recv(1024).decode('utf8', errors='replace') but this not worked

This is the error,

file.txt
Traceback (most recent call last):
  File "d:\Python\FileShare\reciver.py", line 18, in <module>  
    file_size = client.recv(1024).decode('utf8')
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 2: invalid start byte

Solution

  • I found a solution this problem. Change a while loop to the process.

    this is the code I change,

    #for_server_side
    client.send(file_name.encode())
    client.send(str(file_size).encode())
    
    #for_client_side
    file_name = sock.recv(100).decode()
    file_size = sock.recv(100).decode()
    
    with open(file_name, 'rb') as file:
    
    progress = tqdm.tqdm(unit='B', unit_scale=True, unit_divisor=1000, total=int(file_size))
    
    c = 0
    
    while c <= file_size:
        data = file.read(1024)
        if not (data):
            break
        client.sendall(data)
        c += len(data)
    
        progress.update(1024) 
    

    client and server both side make these changes and it is work properly!