1

我在显示文件内容时遇到问题:

def NRecieve_CnD():
    host = "localhost"
    port = 8080
    NServ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    NServ.bind(("localhost",8080))
    NServ.listen(5)
    print("Ballot count is waiting for ballots")
    conn, addr = NServ.accept()
    File = "Ballot1.txt"
    f = open(File, 'w+')
    data = conn.recv(1024)
    print('Ballots recieved initializing information decoding procedures')
    while(data):
        data1 = data.decode('utf8','strict')
        f.write(data1)
        data = conn.recv(1024)
        print("Ballot saved, Now displaying vote... ")
        files = open("Ballot1.txt", "r")
        print(files.read())
    

当程序运行时,应该显示文件内容的区域是空白的。

4

1 回答 1

2

您正在写入文件,然后再次打开文件并且没有显式刷新您的第一次写入,或者通过关闭文件句柄,您正在读取文件。结果是您在完成写入之前正在读取文件。

f.write(data1)
f.flush() # Make sure the data is written to disk
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
files = open("Ballot1.txt", "r")

除此之外,最好不要让文件保持打开的时间超过必要的时间,以避免出现这样的意外:

with open(File, 'w+') as f:
    f.write(data1)

data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")

with open(File, "r") as f:
    print(f.read())
于 2020-11-30T06:22:33.620 回答