ftplib --- FTP 協定用戶端¶
原始碼:Lib/ftplib.py
這個模組定義了 FTP 類別和一些相關的項目。FTP 類別實作了 FTP 協定的用戶端。你可以使用它來編寫能夠執行各種 FTP 自動作業的 Python 程式,例如鏡像 (mirror) 其他 FTP 伺服器。urllib.request 模組也使用它來處理使用 FTP 的 URL。有關 FTP(檔案傳輸協定)的更多資訊,請參閱 RFC 959。
預設編碼是 UTF-8,遵循 RFC 2640。
可用性: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台。
這是一個使用 ftplib 模組的會話範例:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org') # connect to host, default port
>>> ftp.login() # user anonymous, passwd anonymous@
'230 Login successful.'
>>> ftp.cwd('debian') # change into "debian" directory
'250 Directory successfully changed.'
>>> ftp.retrlines('LIST') # list directory contents
-rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README
...
drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool
drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project
drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>> ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
參考¶
FTP 物件¶
- class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8')¶
回傳一個新的
FTP類別實例。- 參數:
host (str) -- 要連接的主機名稱。如果有給定,
connect(host)會由建構函式來隱式地呼叫。user (str) -- The username to log in with (default:
'anonymous'). 如果有給定,login(host, passwd, acct)會由建構函式來隱式地呼叫。passwd (str) -- The password to use when logging in. If not given, and if passwd is the empty string or
"-", a password will be automatically generated.acct (str) -- Account information to be used for the
ACCTFTP command. Few systems implement this. See RFC-959 for more details.timeout (float | None) -- 如
connect()的阻塞操作的超時設定,以秒為單位(預設:使用全域預設超時設定)。source_address (tuple | None) -- A 2-tuple
(host, port)for the socket to bind to as its source address before connecting.encoding (str) -- The encoding for directories and filenames (default:
'utf-8').
>>> from ftplib import FTP >>> with FTP("ftp1.at.proftpd.org") as ftp: ... ftp.login() ... ftp.dir() ... '230 Anonymous login ok, restrictions apply.' dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora >>>
在 3.2 版的變更: 新增了對
with陳述式的支援。在 3.3 版的變更: 新增 source_address 參數。
在 3.9 版的變更: 如果 timeout 參數設定為零,它將引發
ValueError以防止建立非阻塞 socket。新增了 encoding 參數,預設值從 Latin-1 更改為 UTF-8 以遵循 RFC 2640。FTP的多個可用方法大致有分為兩個方向:一種用於處理文本檔案 (text files),另一種用於二進位檔案 (binary files)。這些以在文本檔案的lines或二進位檔案的binary前使用的命令命名。FTP實例具有以下方法: