pythonimageimage-file

Getting all the bytes representing the file from it


I'm creating a server-client code in python and I'm trying to send an image file from the server to the client by reading the bytes of the file and sending it. For some reason the bytes that has been read don't represent an appropriate file that can be seen - when I save the bytes I read as an image they don't give the image I scanned theme from.

    elif command == COMMANDS[1]:
        print(f'Reading the bytes of {params[0]}')
        f = open(params[0], 'rb')
        data = f.read()
        if os.path.exists(r'C:\Users\orlav\Desktop\networking_book_stuff\tech_server\screen2.jpg'):
            os.remove(r'C:\Users\orlav\Desktop\networking_book_stuff\tech_server\screen2.jpg')

        f2 = open(r'C:\Users\orlav\Desktop\networking_book_stuff\tech_server\screen2.jpg', 'wb+')
        f2.write(data)

for some reason f2 doesn't contains what f contains


Solution

  • Opening files both for reading and writing in Python always needs to be inside with block to avoid troubles.

    Correct reading:

    with open(file_name, 'rb') as f:
        data = f.read()
    

    Correct writing:

    with open(file_name, 'wb') as f:
        f.write(data)
    

    with block forces files to be correctly closed and flushed whenever block is finished including a case when block is finished due to exception.

    If file is opened using just open(...) without with then it is not closed/flushed until program finishes if flushed correctly at all. If file was opened for writing and not closed it may be just partially written. If file was opened for reading and not closed deleting this file may cause problems too. Both for reading and writing if not closed memory used for buffers is not released too resulting in huge memory leak when repeated many times open/read is done.

    Always use with block for opening files both for reading and writing to close it correctly after block is finished.