TypeError: a bytes-like object is required, not '_io.BufferedReader'

Viewed 6854

I run this script

# -*- coding: utf-8 -*-
import socket

def snd():
    a = ent.get()
    sock.send(a.encode())
    print("Отправка текста")
def sndfle():
    b = ent2.get()
    file = open(b, "rb")
    sock.send(file)
    print("Отправка файла")


sock = socket.socket()
sock.connect(('localhost', 25565))
print ("Соединение с сервером установлено")

I see this error

    sock.send(file)
TypeError: a bytes-like object is required, not '_io.BufferedReader'

Please help me I run def(s) with buttons. I hide it.

1 Answers

See this question.

You need to get bytes from the file in order to send it over the socket. Try this:

def sndfle():
    b = ent2.get()
    with open(b, "rb") as file:
        for data in file:
            sock.sendall(data)
    print("Отправка файла")
Related