Question

I am trying to download files from a ftp server but I am running into an error permission denied error.

Traceback (most recent call last):
   File "/Users/x34/Documents/Python/ftp_download.py", line 27, in <module>
     download()
   File "/Users/x34/Documents/Python/ftp_download.py", line 21, in download
     with open(filename,'wb') as f:
IOError: [Errno 13] Permission denied: '/p012r018_5dt19900722_z20_30.tif.gz'

Downloading manually or with filezilla works fine but my script below does not

from ftplib import ftp    
ftp = FTP(r'ftp.glcf.umd.edu')
ftp.login()

directory = 'glcf/Landsat/WRS2/p012/r018/p012r018_5dx19900722.TM-GLS1990'
filename = '/p012r018_5dt19900722_z20_30.tif.gz'

ftp.cwd(directory)

with open(filename,'wb') as f:
    ftp.retrbinary('RETR' + filename,f.write)

ftp.close()

One another note... and perhaps I misread the docs - http://docs.python.org/library/ftplib.html but I do not fully understand where ftplib decides to download the files (default download directory?). Is there another module better suited for this application?

UPDATE

I should clarify that the filename on the server does not contain the '/' in front. I simply added that as it appeared to help locate the correct file location and name as prior attempts ended in the following error ftplib.error_perm: 500 Unknown command.

the full path to the file is

 ftp.glcf.umd.edu/glcf/Landsat/WRS2/p012/r018/p012r018_5dx19900722.TM-GLS1990/p012r018_5dt19900722_z20_30.tif.gz'
Was it helpful?

Solution

Its saves your file where you ask it to save, in the line with open(filename,'wb') as f:, you are opening the file to save the received content.

And, as your filename starts with a /, it tries to save to the root (/) of your filesystem, where it looks like you don't have enough permissions.

Try this:

from ftplib import ftp    
ftp = FTP(r'ftp.glcf.umd.edu')
ftp.login()

directory = 'glcf/Landsat/WRS2/p012/r018/p012r018_5dx19900722.TM-GLS1990'
filename = '/p012r018_5dt19900722_z20_30.tif.gz'

ftp.cwd(directory)

with open(filename[1:],'wb') as f: # slices the string, "cutting" out the "/"
    ftp.retrbinary('RETR ' + filename,f.write)

ftp.close()

Notice that we changed the filename to be written in your filesystem (line with open(filename[1:],'wb') as f:). Take a look at this question, if you don't know the slice operator.

Also, you should put a space character in the end of the 'RETR' string in your code. It should be 'RETR ' + filename instead of 'RETR' + filename. 'RETR somefile.txt' is a command to the FTP server, and you were doing 'RETRsomefile.txt', corrupting the command with the filename.

OTHER TIPS

You are using the same filename variable in two places where I assume the root "/" is valid for your ftp but obviously a permission issue locally.

Try using "/" in the ftp command, but without "/" on the local file you are opening

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top