Python-network-programming-python-ftp
提供:Dev Guides
Python-FTP
FTPクラスのメソッド
Pythonでは、ファイルを転送するときにファイルをリストするために、以下に必要なメソッドを持つモジュール ftplib を使用します。
Method | Description |
---|---|
pwd() | Current working directory. |
cwd() | Change current working directory to path. |
dir([path[,…[,cb]]) | Displays directory listing of path. Optional call-back cb passed to retrlines(). |
storlines(cmd, f) | Uploads text file using given FTP cmd - for example, STOR file name. |
storbinary(cmd,f[, bs=8192]) | Similar to storlines() but is used for binary files. |
delete(path) | Deletes remote file located at path. |
mkd(directory) | Creates remote directory. |
exception ftplib.error_temp | Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received.. |
exception ftplib.error_perm | Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received.. |
connect(host[, port[, timeout]]) | Connects to the given host and port. The default port number is 21, as specified by the FTP protocol.. |
quit() | Closes connection and quits. |
以下は、上記のメソッドのいくつかの例です。
ファイルのリスト
以下の例では、ftpサーバーへの匿名ログインを使用し、現在のディレクトリのコンテンツを一覧表示します。 ファイルとディレクトリの名前を処理し、リストとして保存します。 次に、それらを印刷します。
上記のプログラムを実行すると、次の出力が得られます-
ディレクトリを変更する
以下のプログラムは、ftplibモジュールで利用可能なcwdメソッドを使用してディレクトリを変更し、必要なコンテンツを取得します。
上記のプログラムを実行すると、次の出力が得られます-
ファイルの取得
上記のファイルのリストを取得した後、 getfile メソッドを使用して特定のファイルを取得できます。 このメソッドは、ファイルのコピーをリモートシステムからFTP接続が開始されたローカルシステムに移動します。
上記のプログラムを実行すると、接続が開始されたローカルシステムにファイルREADME.nlugが存在することがわかります。