1

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

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
MeatBALL
  • 65
  • 1
  • 8
  • always open files both for reading and writing using `with` block like next `with open(file_name, 'wb') as f: f.write(data)`, Its probably the reason, as you files are not closed. Use `with` for reading and writing, both. – Arty Oct 06 '20 at 12:42
  • Using `with` forces Python to correctly always close the file and flush data when block is finished. Without `with` file remains un-closed and partially written for the whole program run. Also removing file that wasn't closed can be an issue too. – Arty Oct 06 '20 at 12:44
  • @Arty, It worked. Thanks! – MeatBALL Oct 06 '20 at 14:26
  • Created [answer](https://stackoverflow.com/a/64228103/941531). You may upvote and/or accept it if you wish. – Arty Oct 06 '20 at 14:40

1 Answers1

0

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.

Arty
  • 14,883
  • 6
  • 36
  • 69