If you want check if a path belongs to a file or directory, the best solution is what you mentioned already:
ftp = FTP()
ftp.connect(host, port)
ftp.login(user, pass)
# returns True if the path belongs to a file and False if it's a folder
def is_file(path):
try:
ftp.size(path)
return True
except:
return False
But if you want to get list of files or folders inside a folder, you can use mlsd
method. This method returns a dictionary which its keys are names of sub-elements and its values are another dictionary showing attributes of each element, in each value, there's a key named type
which shows type of the element:
cdir
: current(!?) directory (It belongs to .
key)
pdir
: parent directory (It belongs to ..
key)
dir
: directory.
file
: file!
So, for example this function returns the a tuple containing list of files and list of directories:
def ls(path):
files_list = []
directories_list = []
for k, v in ftp.mlsd(path):
if v['type'] == 'file':
files_list.append(k)
elif v['type'] == 'dir':
directories_list.append(k)
return files_list, directories_list