Reputation: 8470
I am trying to list the folders in a ftp directory so that the output is as follows:
[32114, 32115, 32116, ..., 42123]
The following script accesses the ftp site. How can I access the folders in the ftp directory using the attached script as a start?
import arcpy, ftplib, os, socket
HOST = 'atlas.ca.gov'
DIRN = '/pub/naip/2012/doqqs_combined_color-nir/'
workspace = 'F:/download/location'
# Get current working directory
print 'The current working directory is %s' % os.getcwd()
# Change the current working directory to a download folder
os.chdir(workspace)
print 'The workspace has been changed to %s' % workspace
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
print 'ERROR: cannot reach "%s"' % HOST
print '*** Connected to host "%s"' % HOST
try:
f.login()
except ftplib.error_perm:
print 'Error: cannot login anonymously'
f.quit()
print '*** Logged in as "anonymous"'
try:
f.cwd(DIRN)
except ftplib.error_perm:
print 'ERROR: cannot CD to "%s"' % DIRN
f.quit()
print '*** Changed to "%s" folder' % DIRN
Upvotes: 2
Views: 5415
Reputation: 8470
Building on the answer by abarnert, the following produces the list:
from ftplib import FTP
ftp = FTP('atlas.ca.gov')
ftp.login()
ftp.cwd('/pub/naip/2012/doqqs_combined_color-nir/')
print ftp.nlst()
Upvotes: 0
Reputation: 379
If the server is a windows machine, the output of
ftp.dir()
will look like 01-14-14 04:21PM <DIR> Output
If the server is of the *nix variety, the output will look like drwx------ 3 user group 512 Apr 22 2005 Mail
If you want to check if an item is a directory, use a regular expression on each line.
Windows FTP server will contain <DIR>
if the item is a directory and *nix ftp servers will start with d
.
Do you need help with Python regexes?
Upvotes: 1
Reputation: 365717
If you look at the ftplib
docs, there are two obvious functions for this: nlst
and dir
.
Either one will give you a list of all members in the directory, both files and subdirectories.
With nlst
, you don't get any information beyond the name. But if you were planning to chdir
or otherwise use each one of them, that's OK; you will get exceptions for the ones that turned out to be regular file, and can just skip over them.
With dir
, you get a full directory listing, in human-readable form. Which you will have to capture (by passing a callback
function) and then parse manually—which is a lot less fun, but the only way you can know in advance which members are files and which are directories.
Upvotes: 2