歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python FTP 下載文件 簡單示例

Python FTP 下載文件 簡單示例

日期:2017/3/1 9:33:55   编辑:Linux編程

簡單的FTP下載 ,不加任何異常判斷。

import os

from ftplib import FTP

ftp_addr = '10.10.0.1'

f=FTP(ftp_addr)
f.login('anonymous')
f.cwd("apk_download/")
remote_file = '20141223140651.apk'
f.retrbinary("RETR %s" % remote_file, open(remote_file, "wb").write)

還有個帶 異常處理的版本

#! encoding:utf-8
# Filename : ftptestdown.py
#使用ftplib.error_perm函數來打印輸出錯誤信息

import ftplib
import os
import socket

remote_host = "ftp.kernel.org"
remote_dir = "/pub/linux/kernel/v1.0"
remote_file = "patch8.gz"
def kernelmain():
try:
ftp = ftplib.FTP(remote_host)
except (socket.error, socket.gaierror):
print "ERROR cannot reach '%s'" % remote_host
return
print "..Connected to remote_host '%s'.." %remote_host

try:
ftp.login() #使用匿名賬號登陸也就是anonymous
except ftplib.error_perm:
print "ERROR cannot login anonymously"
ftp.quit()
return
print "...logged in as 'anonymously'..."

try:
ftp.cwd(remote_dir) #切換當前工作目錄
except ftplib.error_perm:
print "ERROR cannot cd to '%s'" % remote_dir
ftp.quit()
return
print "....Changed to '%s' folder...." % remote_dir

try:#傳一個回調函數給retrbinary() 它在每接收一個二進制數據時都會被調用
ftp.retrbinary("RETR %s" % remote_file, open(remote_file, "wb").write)
except ftplib.error_perm:
print "ERROR cannot remote_file '%s'" % remote_file
os.unlink(remote_file)
else:
print ".....Download '%s' to cwd....." % remote_file

ftp.quit()
return

#調用函數執行測試
if __name__ == "__main__":
kernelmain()

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved