Checking if object on FTP server is file or directory using Python and ftplib
<p>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.</p>

<pre><code>file_type = ''
try:
    ftp.cwd(item_name)
    file_type = 'dir'
    ftp.cwd(cur_path)
except ftplib.error_perm:
    file_type = 'file'
</code></pre>

<p>I have scoured the internet and library documentation for other methods, but I cannot find ones that would work on most cases.</p>

<p>For example using the <code>dir</code> function, I can check if the first character is <code>'d'</code> and this might determine it, however further reading has indicated that not all output is of the same format.</p>

<p>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.</p>

<p>Is there something I am missing or a cleaner way to do this?</p>