Search code examples
pythonpython-3.9

Displaying the contents of the file


I'm having problems with displaying the contents of the file:

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

when the program is run the area where the contents of the file are supposed to be shown is blank.


Solution

  • You're writing to a file, then opening the file again and without flushing your first write either explicitly, or by closing the file handle, you're reading a file. The result is you're reading the file before you finish writing it.

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

    Beyond that, it's probably best if you don't keep the file open for longer than necessary to avoid surprises like this:

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