手元のパソコンからレンタルサーバにファイルをアップロードする場合はFTPソフトを使うと思います。
Pythonを使うとFTPソフトなしでファイルをアップロードすることができます。
FTP接続
from ftplib import FTP
ftp = FTP(
host = "ftp.dp00000000.lolipop.jp",
user = "lolipop.jp-dp00000000",
passwd = "xxxxxxxx"
)
ftp = FTP(
host = "ftp.dp00000000.lolipop.jp",
user = "lolipop.jp-dp00000000",
passwd = "xxxxxxxx"
)
まずftplibをインポートします。標準なのでインストール不要です。
host, user, passwd はご自分のものをセットしてください。
ここではロリポップの場合を例として挙げています。
テキストファイルのアップロード
fn_src = "abc.txt"
fn_dst = "/python/def.txt"
with open(fn_src, "rb") as f:
ftp.storlines("STOR " + fn_dst, f)
fn_dst = "/python/def.txt"
with open(fn_src, "rb") as f:
ftp.storlines("STOR " + fn_dst, f)
手元にあるabc.txtをサーバのpythonというフォルダにdef.txtという名前でアップロードします。
画像ファイルのアップロード
fn_src = "magician.jpeg"
fn_dst = "/python/magician.jpeg"
with open(fn_src, "rb") as f:
ftp.storlines("STOR " + fn_dst, f)
fn_dst = "/python/magician.jpeg"
with open(fn_src, "rb") as f:
ftp.storlines("STOR " + fn_dst, f)
画像ファイルもテキストファイルと同様にアップロードできます。
テキストファイルのダウンロード
fn_src = "/python/def.txt"
fn_dst = "ghi.txt"
with open(fn_dst, "w") as f:
ftp.retrlines("RETR " + fn_src, f.write)
fn_dst = "ghi.txt"
with open(fn_dst, "w") as f:
ftp.retrlines("RETR " + fn_src, f.write)
サーバのpythonというフォルダのdef.txtを手元のパソコンにghi.txtという名前でダウンロードします。
コメント