python3ftplib:通过mlsd()检查dir是否存在

2024-10-01 11:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Python3和ftplib。在

我需要检查ftp服务器上是否存在目录。(如果没有,我可以创建它,而不是cwd到它,如果它已经存在,我将直接cwd到它中)。在

我在这里看到了Marek Marecki的方法:How to make Python check if ftp directory exists?

if 'foo' in [name for name, data in list(remote.mlsd())]:

这样的问题也会在名为“foo”的文件上触发。在

有没有一种python方法来实现这一点(显式地使用mlsd())?nlst()已弃用

非常感谢!在


Tags: 方法namein服务器目录iffooftp
2条回答

也要感谢@arnial

我有以下建议:(mlsd或nslt)

use_mlsd = 1
if(use_mlsd):
  # if ftp server supports mlsd, use it, nlst is maked as deprecated in ftplib
  # check if remotefoldername exists
  remotefoldername_exists = 0
  for name, facts in f.mlsd(".",["type"]):
    if facts["type"] == "dir" and name == "remote_ftp":
      print("isdir: "+ name)
      remotefoldername_exists = 1
      break
  if(remotefoldername_exists == 0)
    ftp.mkd(remotefoldername)
    logging.debug("folder does not exitst, ftp.mkd: " + remotefoldername)
  else:
    logging.debug("folder did exist: " + remotefoldername)

else:
    # nlst legacy support for ftp servers that do not support mlsd e.g. vsftp
    items = []
    ftp.retrlines('LIST', items.append ) 
    items = map( str.split, items )
    dirlist = [ item.pop() for item in items if item[0][0] == 'd' ]
    #print( "directrys", directorys )
    #print( 'remote_ftp' in directorys )
    if not (remotefoldername in dirlist):
      ftp.mkd(remotefoldername)
      logging.debug("folder does not exitst, ftp.mkd: " + remotefoldername)
    else:
      logging.debug("folder did exist: " + remotefoldername)

我没有任何服务器支持MLSD命令,所以我不确定如何使用MLSD来实现这一点。 但是即使没有MLSD的支持,这个代码也应该可以工作。在

    items = []
    ftp.retrlines('LIST', items.append ) 
    items = map( str.split, items )
    directorys = [ item.pop() for item in items if item[0][0] == 'd' ]
    print( "directrys", directorys )
    print( 'foo' in directorys )

相关问题 更多 >