2012-05-17 22 views
8

私はpythonでftpでファイルを転送するためにpycurlを使っていました。私が使用して私のリモートサーバー上で自動的に不足しているディレクトリを作成することができます。いくつかの理由でftplib storbinaryで見つからないディレクトリを作成する

c.setopt(pycurl.FTP_CREATE_MISSING_DIRS, 1) 

を、私はftplibのに切り替える必要があります。しかし、私はここで同じようにする方法を知らない。そのためにstorbinary関数に追加するオプションはありますか?または手動でディレクトリを作成する必要がありますか?

答えて

9

FTP_CREATE_MISSING_DIRSは、カール操作(added here)です。 ftplibで手作業で行う必要があると思いますが、間違っていると誰かが証明したいですか? (未テスト、およびftplib.all_errorsをキャッチする必要があります)

ftp = ... # Create connection 

# Change directories - create if it doesn't exist 
def chdir(dir): 
    if directory_exists(dir) is False: # (or negate, whatever you prefer for readability) 
     ftp.mkd(dir) 
    ftp.cwd(dir) 

# Check if directory exists (in current location) 
def directory_exists(dir): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    for f in filelist: 
     if f.split()[-1] == dir and f.upper().startswith('D'): 
      return True 
    return False 

それとも、このようdirectory_existsを行うことができます:(?読み少し難しい)私は、次のような何かをしたい

# Check if directory exists (in current location) 
def directory_exists(dir): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    return any(f.split()[-1] == dir and f.upper().startswith('D') for f in filelist) 
+1

ありがとう、私が探していたものではありませんでしたが、それは良い答えでした。 Thanx;) – AliBZ

+1

いいえ、手動で行う必要はありません。代わりに 'ftputil'パッケージの' makedirs'メソッドを呼び出すことができます。 – xApple

4

これを@Alex Lの答えにコメントとして追加しようとしましたが、長すぎます。途中でディレクトリを作成する場合は、ディレクトリを変更するときに再帰的に下降する必要があります。例えば。

def chdir(ftp, directory): 
    ch_dir_rec(ftp,directory.split('/')) 

# Check if directory exists (in current location) 
def directory_exists(ftp, directory): 
    filelist = [] 
    ftp.retrlines('LIST',filelist.append) 
    for f in filelist: 
     if f.split()[-1] == directory and f.upper().startswith('D'): 
      return True 
    return False 

def ch_dir_rec(ftp, descending_path_split): 
    if len(descending_path_split) == 0: 
     return 

    next_level_directory = descending_path_split.pop(0) 

    if not directory_exists(ftp,next_level_directory): 
     ftp.mkd(next_level_directory) 
    ftp.cwd(next_level_directory) 
    ch_dir_rec(ftp,descending_path_split) 
6

私はそれが古い投稿のようなものだと知っていますが、私はこれを必要とし、非常に単純な機能を思いついた。私はPythonの初心者ですので、フィードバックをいただければ幸いです。

from ftplib import FTP 

ftp = FTP('domain.com', 'username', 'password') 

def cdTree(currentDir): 
    if currentDir != "": 
     try: 
      ftp.cwd(currentDir) 
     except IOError: 
      cdTree("/".join(currentDir.split("/")[:-1])) 
      ftp.mkd(currentDir) 
      ftp.cwd(currentDir) 

使用例:

cdTree("/this/is/an/example") 
+2

非常にいいです! 'dir'はビルドインされたPythonです。その変数名を変更したいかもしれません...特定の例外をキャッチしたいのですが、すべてではありません – xApple

+0

xAppleに感謝します。私は 'dir'を置き換え、IOErrorの例外を捕捉するように制限しました。 – lecnt

+0

'dir'変数のインスタンスを置き換えるのを忘れたと思います。 – xApple

0

パスに不足しているすべてのフォルダを作成します。このコード:

... 

def chdir(ftp_path, ftp_conn): 
    dirs = [d for d in ftp_path.split('/') if d != ''] 
    for p in dirs: 
     print(p) 
     check_dir(p, ftp_conn) 


def check_dir(dir, ftp_conn): 
    filelist = [] 
    ftp_conn.retrlines('LIST', filelist.append) 
    found = False 

    for f in filelist: 
     if f.split()[-1] == dir and f.lower().startswith('d'): 
      found = True 

    if not found: 
     ftp_conn.mkd(dir) 
    ftp_conn.cwd(dir) 

if __name__ == '__main__': 
    ftp_conn = ... # ftp connection 
    t = 'FTP/for_Vadim/1/2/3/' 

    chdir(t, ftp_conn) 

行方不明のdirs

をパス内のすべてのdirsをチェックして、作成されます。このコードFTP/for_Vadim/1/2/3 /の後に "FTP/for_Vadim /"の前に

関連する問題