LoginSignup
13

More than 5 years have passed since last update.

PythonでFTPからダウンロード

Last updated at Posted at 2018-01-10

概要

・FTPサーバ機能を有するデータロガーより自動でデータをダウンロードしたい。

試行錯誤

・ダウンロード対象はその日毎のcsvファイル一式
・wgetコマンドをFTPサーバへ向けるがうまくダウンロードしない。
・このコマンドはHTMLサーバ向け?
・そこでPythonに任せた

コード

from ftplib import *
import io
import sys
import os

ftp = FTP('192.168.***.***')
ftp.login('user', 'password')
ftp.cwd('/CF/ENR1/Log/') #サーバの対象フォルダ
ftemp = ftp.nlst('.') 
for file in ftemp:
    files = file[len('/CF/ENR1/Log/')-7:] #パス名./を削除
    print(file)
    with open('../data/ENR1/' + file, 'wb') as f: #ローカルパス
        ftp.retrbinary('RETR %s' % file, f.write)
ftp.quit()

#本当は何度も同じコマンドを発行しない?
ftp = FTP('192.168.***.***')
ftp.login('user', 'password')
ftp.cwd('/CF/SENSOR/Log/')
ftemp = ftp.nlst('.')
for file in ftemp:
    files = file[len('/CF/SENSOR/Log/')-7:]
    print(file)
    with open('../data/SENSOR/' + file, 'wb') as f:
        ftp.retrbinary('RETR %s' % file, f.write)
ftp.quit()

終わりに

・cron使えば勝手にダウンロードしてくれる。
・ローカル側にファイルが既にあるか確認はしていない。
・コードはもっと簡単にできるはず。
・いろんなコメントお待ちします。

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
13