如果只是想下载文件,那么urllib2模块就可以轻松完成这个任务,而且比FTP更简单,但是FTP一些特殊功能urllib2模块不具备。(网络编程基础P277)
- #!/usr/bin/python
- #-*- coding:UTF-8 -*-
-
- from ftplib import import FTP
-
- f = FTP('ftp.ibiblio.ort')
- print "Welcome:", f.getwelcome()
- f.login()
-
- print "CWD:", f.pwd()
- f.quit()
以ASCII模式下载文件
- #!/usr/bin/python
- #-*- coding:UTF-8 -*-
-
- from ftplib import import FTP
-
- def writeline(data):
- fd.write(data + "\n")
-
- f = FTP('ftp.kernel.ort')
- f.login()
-
- f.cwd('/pub/linux/kernel')
- fd = open('README', 'wt')
- f.retrlines('RETR README', writeline)
- fd.close()
-
- f.quit()
以二进制模式下载文件
- #!/usr/bin/python
- #-*- coding:UTF-8 -*-
-
- from ftplib import import FTP
-
- f = FTP('ftp.kernel.ort')
- f.login()
-
- f.cwd('/pub/linux/kernel/v1.0')
- fd = open('patch8.gz', 'wb')
- f.retrbinary('RETR patch8.gz', fd.write)
- fd.close()
-
- f.quit()
以高级二进制模式下载文件
- #!/usr/bin/python
- #-*- coding:UTF-8 -*-
-
- from ftplib import import FTP
- import sys
-
- f = FTP('ftp.kernel.ort')
- f.login()
-
- f.cwd('/pub/linux/kernel/v1.0')
- f.voidcmd("TYPE I")
-
- datasock, estsize = f.ntransfercmd("RETR linux-1.0.tar.gz")
- transbytes = 0
- fd = open('linux-1.0.tar.gz', 'wb')
- while 1:
- buf = datasock.recv(2048)
- if not len(buf):
- break
- fd.write(buf)
- transbytes += len(buf)
- sys.stdout.write("Received %d" % transbytes)
-
- if estsize:
- sys.stdout.write("of %d bytes (%.1f%%)\r" % (estsize, 100.0 * float(transbytes) / float(estsize)))
- else:
- sys.stdout.write("bytes\r")
- sys.stdout.flush()
- sys.stdout.write("\n")
- fd.close()
- datasock.close()
- f.voidresp()
-
- f.quit()