Search code examples
pythonpython-3.9

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


I'm trying to send a file over a network and this piece of code is giving me some trouble:

def Network_Vinfo():
    Uinfo = [] # list call
    host = "localhost"
    port = 8080
    Nvi = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Nvi.connect((host, port))
    
    print("Connected to Server, Initializing voting procedures.")#Sever is connected
    
    with open("ballot1.txt", "w+") as ballot:# creating the file
        A =str(input("Enter your name"))#Info asking for users info to count "Vote"
        b = str(input("Enter your Address"))
        c =str(input("Enter your Driver License No."))
        print('Candidates: John Ossoff, Raphael Warnock, David Perdue, Kelly loeffler')
        d =str(input("Enter your Preferred Candidate"))
        Uinfo = [A,b,c,d]
        #write items in list on Newline
        for U in Uinfo:
            ballot.write('%s\n' % U)
        data = ballot
        while (data):
           Nvi.sendall(ballot)
           data = ballot.read(1024)
           print("finished sending")

The problem starts where the program tries to send the file in the while(data) loop. Please help I am very desperate!


Solution

  • You must send the data read from the file, not the file object.

    The last part of your code should be like:

    ballot.seek(0)
    data = ballot.read(1024)
    while (data):
        Nvi.sendall(data)
        data = ballot.read(1024)
    print("finished sending")