Checking if object on FTP server is file or directory using Python and ftplib(使用 Python 和 ftplib 检查 FTP 服务器上的对象是文件还是目录)
问题描述
使用 Python 和 ftplib,我正在编写一个通用函数来检查 FTP 目录中的项目是文件还是目录.由于使用 MLSD 功能可能不一定适用于所有服务器(我的一个用例没有提供),因此我采用了这种有效但粗略的方式来确定它,尝试将目录更改为对象,如果对象是一个文件,引发异常并相应地设置文件类型.
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.
例如使用 dir
函数,我可以检查第一个字符是否是 'd'
这可能会确定它,但是进一步阅读表明并非所有输出格式相同.
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?
推荐答案
没有更好的方法(一般使用 FTP 协议,而不仅仅是使用 ftplib).
There's no better way (with FTP protocol in general, not just with ftplib).
MLST
/MLSD
是唯一正确可靠的方法.
The MLST
/MLSD
is the only correct and reliable way.
如果您不能使用 MLST
/MLSD
,尝试 CWD
是下一个最佳选择.
If you cannot use MLST
/MLSD
, trying CWD
is the next best option.
尝试解析 LIST
是一个后备选项.但是您需要知道服务器使用您的程序可以理解的列表格式.
Trying to parse LIST
is a fallback option. But you need to know that the server uses listing format your program understands.
这篇关于使用 Python 和 ftplib 检查 FTP 服务器上的对象是文件还是目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!