如何在 Python 中使用 FTP?
在 Python 中,我們可以透過匯入 ftplib 模組來使用 FTP(檔案傳輸協議),它將提供一個簡單的介面來訪問 FTP 伺服器,以檢索檔案並在本地處理它們。ftplib 模組允許我們編寫執行各種自動化 FTP 任務的 Python 程式。
FTP 的目標
FTP 的目標如下
- FTP 提供檔案共享。
- FTP 有助於我們鼓勵使用遠端計算機。
- FTP 用於可靠且高效地傳輸資料。
以下是一些我們可以使用 FTP 在 Python 中透過利用 'ftplib' 模組執行的常見任務
- 連線到 FTP 伺服器
- 下載檔案
- 上傳檔案
- 列印檔案列表
連線到 FTP 伺服器
以下將連線到遠端伺服器,然後我們可以將其更改為特定目錄。
from ftplib import FTP #domain name or server ip: ftp = FTP('123.server.ip') ftp.login(user='username', passwd = 'password'
在執行上述連線 FTP 伺服器的程式時,如果連線成功,它將顯示 “登入成功。”
'230 Login successful.'
如果連線失敗,由於使用者名稱或密碼錯誤,它將顯示 “登入錯誤。”
'530 Login incorrect.'
下載檔案
首先,我們必須將檔名分配給一個變數,並使用 open() 方法開啟我們的本地檔案。除了檔名之外,您還需要傳遞表示所需模式的字串。在我們的場景中,我們需要下載的檔案是二進位制檔案,因此模式將為 wb.
接下來,我們必須從遠端伺服器檢索以二進位制格式存在的資料,然後將我們找到的內容寫入本地檔案。最後一個引數 (1024) 充當緩衝區的參考。
from ftplib import FTP def download_file(): # Establish FTP connection ftp = FTP('ftp.example.com') ftp.login('username', 'password') # Define the file to be downloaded file_name = 'example.txt' # Open a local file in write-binary mode with open(file_name, 'wb') as local_file: # Download the file from the FTP server ftp.retrbinary('RETR ' + file_name, local_file.write, 1024) # Quit the FTP connection ftp.quit() print(f"{file_name} downloaded successfully!") # Call the function download_file()
以下是上述程式碼的輸出 -
example.txt downloaded successfully!
上傳檔案
與下載檔案相同,這裡我們將檔名分配給一個變數,然後將二進位制資料儲存到檔名中,並使用本地檔案中的資料。
def upload_file(): file_name = 'exampleFile.txt' ftp.storbinary('STOR ' + file_name, open(file_name, 'rb')) ftp.quit() upload_file()
列印檔案列表
以下示例程式碼將連線到 FTP 伺服器並列印該伺服器主目錄中的檔案列表。
import ftplib # Connect to the FTP server ftp_connection = ftplib.FTP('ftp.server.com', 'username', '@email.address') # Printing file list print("File List:") file_list = ftp_connection.dir() print(file_list) # Change working directory to /tmp ftp_connection.cwd("/tmp")
以下是上述程式碼的輸出 -
File List: -rw-r--r-- 1 owner group 12345 Sep 11 12:00 file1.txt -rw-r--r-- 1 owner group 67890 Sep 10 15:30 file2.zip
廣告