Using Python and ftplib, I'm writing a generic function to check whether the items in an FTP directory are either files or directories. Since using the MLSD function might not necessarily work with all servers ( one of my use cases does not provide for it ) I have resorted to this effective but crude manner of determining it, by attempting to change directory to the object and if the object is a file, an exception is raised and the file type is set accordingly.
file_type = ''
try:
ftp.cwd(item_name)
file_type = 'dir'
ftp.cwd(cur_path)
except ftplib.error_perm:
file_type = 'file'
I have scoured the internet and library documentation for other methods, but I cannot find ones that would work on most cases.
For example using the dir
function, I can check if the first character is 'd'
and this might determine it, however further reading has indicated that not all output is of the same format.
The biggest flaw I can see in this method is if I do not have permission to change directory to the specified folder; hence it will be treated as a file.
Is there something I am missing or a cleaner way to do this?