Python - 資料上傳



我們可以使用處理 FTP 或檔案傳輸協議的 Python 模組將資料上傳到伺服器。

我們需要安裝模組 ftplib 來實現此目的。

pip install ftplib

使用 ftplib

在下面的示例中,我們使用 FTP 方法連線到伺服器,然後提供使用者憑證。接下來,我們指定檔名稱和 storbinary 方法,以便在伺服器中傳送和儲存檔案。

import ftplib

ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "password")
file = open('index.html','rb')   
ftp.storbinary("STOR " + file, open(file, "rb"))
file.close()                                   
ftp.quit() 

當執行上述程式時,我們觀察到已在伺服器中建立了該檔案的副本。

使用 ftpreety

類似於 ftplib,我們可以使用 ftpreety 安全地連線到遠端伺服器並上傳檔案。我們還可以使用 ftpreety 下載檔案。下面的程式說明了這一點。

from ftpretty import ftpretty

# Mention the host
host = "127.0.0.1"

# Supply the credentisals
f = ftpretty(host, user, pass )

# Get a file, save it locally
f.get('someremote/file/on/server.txt', '/tmp/localcopy/server.txt')

# Put a local file to a remote location
# non-existent subdirectories will be created automatically
f.put('/tmp/localcopy/data.txt', 'someremote/file/on/server.txt')

當執行上述程式時,我們觀察到已在伺服器中建立了該檔案的副本。

廣告