首页 > 解决方案 > TypeError:需要一个类似字节的对象,而不是'_io.TextIOWrapper'

问题描述

我正在尝试通过网络发送文件,这段代码给我带来了一些麻烦:

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")

问题从程序尝试在 while(data) 循环中发送文件的地方开始。请帮助我很绝望!

标签: pythonpython-3.9

解决方案


您必须发送从文件读取的数据,而不是文件对象。

你的代码的最后一部分应该是这样的:

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

推荐阅读