Downloading files from ftp server using python but files not opening after downloading

Gavya Mehta :

I am using python to download files from a ftp server and i am able to download the files but when i open the files they seem to be corrupted or are not opening Files like songs or jpgs are working fine but documents,excel sheets,pdfs and text files are not downloading properly.

Following is my code :

from ftplib import FTP
ftp = FTP()
direc='directory path'
doc='doc.txt' or xlsx or pdf or jpg etc
download_path='path to download file on desktop'
file=open(download_path+ doc,'wb')
ftp.retrbinary(f"RETR {doc}", file.write)

I am able to download the required files but most of them are neing corrupted. What changes should i make to make the code work.

t3hSeb :

cannot test FTP at the moment but what I see is an issue with your file opening and not closing.

Option A:

file=open(download_path + doc,'wb')  # add '+' to append instead of overwriting

Option B (context manager, useful as it closes file as you finish up):

with open(download_path + doc,'wb') as file:
    file.write(*args, **kwargs)

Regarding use of module ftplib, excellent response at the following post ftp.retrbinary() help python by steveha.

Regarding opening and writing to a file using context manager, see How to open a file using the open with statement, and handling exceptions (Python 3 documentation), as quoted by sir-snoopalot

Check also the ftplib module documentation for further clarification.

Hope this helps.

Guess you like