6

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()
ftp.connect(ip_address,port)
ftp.login(userid,password)
direc='directory path'
ftp.cwd(direc)
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.

3 Answers3

4

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
...
...
file.close()

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.

Seb
  • 72
  • 5
2

I have not tried your code, but looking at Python documentation you may have forgotten to close the file and quit properly, so the file buffer may not be fully written on disk.

Try this:

with open(download_path+ doc,'wb') as fp:
    ftp.retrbinary(f"RETR {doc}", file.write)

ftp.quit()

The with statement will execute the close function for the file when exiting this block

  • Could you also let me know how to download an entire folder instead of just a file –  Apr 03 '20 at 12:28
0

You forgot to close your file. Just add the following at the end of your code.

file.close()
Hamza Khurshid
  • 765
  • 7
  • 18