简体   繁体   中英

Python File Can't Write

I try to make a file transfer script, but it's not working. I receive data, the file is created, but nothing in write in it. In this while block, data are receive once, after that nothing is happend, but the while seems to continue, cause I don't get "File received".

def receive_bytes_data(conn,filename):
    with open("new_file.txt", 'wb') as f:
        while True:
            receive_b = conn.recvfrom(BUFFER_SIZE)[0]
            f.write(receive_b)
            print(receive_b)
            if not receive_b:
                break 
            print(True)
        f.close()
    print("File received")

You're not flushing the buffer to the file in your f.write(..) , so the process waits until the file is closed before doing so. Since you're in an infinite loop, that will never happen.

Either include line_buffering=True in your f.write(..) , or specifically call f.flush() after writing.

My preference is to use the first choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM