LoginSignup
2
7

More than 3 years have passed since last update.

PythonでFTPを使う方法

Posted at

はじめに

Pythonでftpを使用する機会がありましたのでメモとして残しておきます。

FTP接続

import ftplib

ftp = ftplib.FTP(IP_ADDRESS)
ftp.set_pasv('true')
ftp.login(USER, PASSWORD)

*処理の最後には、ftp.close()を忘れずに

ファイルのアップロード(テキスト)

with open("a.txt", "rb") as f:
    ftp.storlines("STOR /aa.txt", f)

*rbバイナリーモードで開く必要あり(バイナリー)

ファイルのアップロード(binary)

with open("b.txt.zip", "rb") as f:
    ftp.storbinary("STOR /bb.zip", f)

ファイルのダウンロード(テキスト)

with open("b.txt", "w") as f:
    ftp.retrlines("RETR /aa.txt", f.write)

ファイルのダウンロード(binary)

with open("b.txt.zip", "wb") as f:
    ftp.retrbinary("RETR /bb.zip", f.write)

with を使用しない場合はこんな感じ

# バイナリは rb、テキストの場合は r 
f = open(filename, 'rb') 
ftp.storbinary('STOR {}'.format(PATH), f)

*この場合は、必ずf.close() をして下さい

ディレクトリ作成

ftp.mkd("XXX")

ファイルの一覧の取得

file_list = ftp.nlst(".")
print(file_list)

エラー処理


try:
    # process
except ftplib.all_errors as e:
        print('FTP Error :', e)

参考文献

2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7