Reputation: 6450
I am trying hard to implement this function:
change the directories if they are present in FTP and if not, create them and change directories to it.
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)
Function calls:
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")
This code currently works if any new directory is given as the parameter
and if the existing directory is given, this traceback comes.
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
My Code Function call logic:
directory = '/new'
ftp_obj.directory_exists(directory)
Upvotes: 1
Views: 2060
Reputation: 6450
I solved this by little trick.
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)
Now, Everything works fine.
Upvotes: 1
Reputation: 3908
Probably ftp.nlst
returns the directory names in a format that does not exactly match the format you are using ('newdir' vs. './newdir' vs. '/full/path/newdir'). However, ftp.mkd
throws an exception, rather than returning False, when you try to create a directory that already exists. With this in mind, you could just change directory_exists
to always try to create the directory, and then chdir regardless of whether it succeeds:
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)
Upvotes: 0