2014-01-17 116 views
1

我努力來實現這個功能:如果它們存在於FTP,如果沒有更改目錄在Python,不工作

變化的目錄,創建和改變目錄到它

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

'if ftp.cwd(directory):''cwd''通常表示「當前工作目錄」。你可能根本沒有改變目錄,只是得到當前的那個 – goncalopp

+0

這不是''和'工作的方式...... – jonrsharpe

+1

@goncalopp當給出服務器**中不存在的新目錄**時,它使該目錄和光盤成功。 – ajkumar25

回答

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) 

現在,一切工作正常。

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)