我正在努力实现这个功能:
更改目录,如果它们存在于FTP中,如果不存在,则创建它们并将目录更改为。
def directory_exists(self, directory_name):
if directory_name in ftp.nlst():
self.change_directory(directory_name)
else:
self.make_directory(directory_name) and self.change_directory(directory_name)
函数调用:
def make_directory(self, directory):
if ftp.mkd(directory):
self.log_message("Directory {0} created successfully".format(directory))
return True
else:
self.log_message("Failed creating directory")
return False
def change_directory(self, directory):
if ftp.cwd(directory):
self.log_message("Current Directory is now {0}".format(ftp.pwd()))
else:
self.log_message("Can't change Directory")
如果任何新目录作为parameter
给出,则此代码当前有效,如果给出了现有目录,则会返回此回溯。
Traceback (most recent call last):
File "C:/Users/Ajay/PycharmProjects/database/config.py", line 17, in <module>
ftp_obj.directory_exists(directory)
File "C:\Users\Ajay\PycharmProjects\database\ftp.py", line 51, in directory_exists
self.make_directory(directory_name) and self.change_directory(directory_name)
File "C:\Users\Ajay\PycharmProjects\database\ftp.py", line 34, in make_directory
if ftp.mkd(directory):
File "C:\Python27\lib\ftplib.py", line 568, in mkd
resp = self.sendcmd('MKD ' + dirname)
File "C:\Python27\lib\ftplib.py", line 244, in sendcmd
return self.getresp()
File "C:\Python27\lib\ftplib.py", line 219, in getresp
raise error_perm, resp
ftplib.error_perm: 550 Can't create directory: File exists
我的代码函数调用逻辑:
directory = '/new'
ftp_obj.directory_exists(directory)
答案 0 :(得分:1)
我通过小技巧解决了这个问题。
def directory_exists(self, directory_name):
new_dir_name = directory_name.strip("/")
if new_dir_name in ftp.nlst():
self.change_directory(directory_name)
else:
self.make_directory(directory_name)
self.change_directory(directory_name)
现在,一切正常。
答案 1 :(得分:0)
可能ftp.nlst
以与您正在使用的格式不完全匹配的格式返回目录名称('newdir'与'./newdir'对比'/ full / path / newdir')。但是,当您尝试创建已存在的目录时,ftp.mkd
会抛出异常,而不是返回False。考虑到这一点,您可以更改directory_exists
以始终尝试创建目录,然后更改chdir而不管它是否成功:
def directory_exists(self, directory_name):
try:
ftp.mkd(directory_name)
self.log_message("Directory {0} created successfully".format(directory))
except ftplib.error_perm:
pass #you could check for other errors also
self.change_directory(directory_name)