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

3

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.

Ladawnladd answered 3/4, 2020 at 8:49 Comment(2)
Maybe this helps: #16019221Dramaturgy
It doesn't seem to work for me.. The files are not even downloading nowLadawnladd
G
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.

Grist answered 3/4, 2020 at 9:14 Comment(0)
O
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

Ohalloran answered 3/4, 2020 at 9:16 Comment(1)
Could you also let me know how to download an entire folder instead of just a fileLadawnladd
A
0

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

file.close()
Atticism answered 3/4, 2020 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.