---
title: Python Module - Ftplib
tags: python, module, ftplib
---
# Module - ftplib
[ftplib document](https://docs.python.org/3/library/ftplib.html)
[不錯的參考資料](https://www.cnblogs.com/xiao-apple36/p/9675185.html)
## FTP Class
### Attrbution
- encoding
- Default is `latin-1`
- `ftp.encoding = 'utf-8'` 解決中文編碼問題
### Function
- FTP(*host*)
- Return: FTP instance
```python=
server = FTP('ftp.ncnu.edu.tw')
# OR
with FTP('ftp.ncnu.edu.tw') as ftp_server:
ftp_server.login()
...
```
- login(*user='anonymous', passwd='', acct=''*)
- If login with anonymous, passwd = anonymous@
```python=
ftp_server.login() # Anonymous login
```
- getwelcome()
- pwd()
- Return current working directory
- dir(*callback function*)
- 列出的資料比較詳細
- 把每一行的資料傳給`callback function`
- 若沒有callback,則印在`stdout`
- nlst()
- Return a list of file/directory names
- mkd(*dir name*)
- Create new directory
- `Return`: full path of the `dir name`
- If directory exists, raise `error_perm: 550 Create directory operation failed.`
- cwd(*path*)
- change current directory to `path`
- retrlines(*cmd, handle function*)
- `cmd`: should be an RETR command: `'RETR filename'`
- Usage: Download ASCII textplain file
- 接收到一行的文字內容丟到handle function
```python=
ftp.retrlines(f'RETR {filename}', print)
```
- retrbinary(*cmd, handle function*)
- `cmd`: should be an appropriate RETR command: `'RETR filename'
- 接收到的位元組內容丟到handle function
```python=
ftp_server.retrbinary(f'RETR {filename}', fd.write)
```
- ntransfercmd(*cmd*)
- Return (socket, estimated size)
- size 僅供參考
```python=
socket, size = ftp.ntransfercmd(f'RETR {filename}')
```
- storbinary(*cmd, fp, blocksize=8192*)
- `cmd`: an appropriate `STOR` command, like `STOR filename`
- `fp`: file object which is `rb` mode
- 儲存檔案至FTP Server
- sendcmd(*cmd*)
- Send command to ftp sever
- Return the response string
- voidcmd(*cmd*)
- Send command to ftp sever
- Return nothing if a response code corresponding to success (codes in 200–299)
- quit()
- Send a QUIT command to the server and close the connection.
## Example
### Get directory
```python=
import ftplib
ftp_server = ftplib.FTP('ftp.ncnu.edu.tw')
ftp_server.login()
data = []
ftp_server.dir(data.append)
ftp_server.quit()
for line in data:
print(line)
```
### Get file
```python=
import ftplib, sys
fname = sys.argv[1]
ftp_server = ftplib.FTP('ftp.ncnu.edu.tw')
ftp_server.login()
# This will output the file content to the stdout
ftp_server.retrlines("RETR " + fname)
# This will save the file content into the local file
with open(fname, 'wb') as fd:
ftp_server.retrbinary("RETR " + fname, fd.write)
ftp_server.quit()
```
### Put file
```python=
import ftplib, sys
fname = sys.argv[1]
ftp_server = ftplib.FTP('ftp.ncnu.edu.tw')
ftp_server.login()
fd = open(fname, 'rb')
ftp_server.storbinary("STOR " + fname, fd)
ftp_server.quit()
```