0
下面的腳本會從ftp站點不是我想要下載的實際文件只下載的文件名下載的所有文件,爲什麼文件大小保持在下載後爲0。你有什麼想法是什麼導致問題?任何幫助將不勝感激。Python的 - 從ftp目錄
import os
from ftplib import FTP
import time
# Connects to remote ftp server
def connect_ftp(hostname, username, password, source_directory, destination_directory):
os.chdir(destination_directory)
print("Connecting to " + hostname + "...")
ftp = FTP(hostname)
ftp.login(username, password)
print(ftp.getwelcome())
print("Connected Successfully!\n")
ftp.cwd(source_directory)
download_files(ftp)
# Download files
def download_files(ftp):
print("This script will only download files, not directories.")
print("Files at " + source_directory + ":\n")
ftp.retrlines("LIST")
file_list = []
ftp.retrlines("NLST", file_list.append)
print("")
i = 0
for filename in file_list:
if (filename != '.') and (filename != '..'):
print("Downloading " + filename + "...")
try:
ftp.retrbinary("RETR " + filename, open(filename, "wb").write)
i=i+1
except Exception as directory_error:
print ("Oops! Was " + filename + " a directory? I won't download directories.")
print(str(i) + " files successfully downloaded.\n")
disconnect_ftp(ftp)
# Disconnects from ftp server
def disconnect_ftp(ftp):
print("Disconnecting from " + hostname + "...")
ftp.quit()
print("Disconnected from " + hostname + ".")
time.sleep(4)
hostname = "ftpsite" # TODO: Replace with the hostname of the server you want to connect to
username = "" # TODO: Replace the username
password = "" # TODO: Replace the password
source_directory = "/source/directory/" # TODO: Change location to wherever you want to start the download
destination_directory = "C:\example\FTP" # TODO: Change the location of where you want to download the files to
connect_ftp(hostname, username, password, source_directory, destination_directory)
下載目錄中的所有文件在本質上是一樣的下載目錄,所有你需要做的就是先創建一個目標目錄具有相同的名稱作爲一個上源文件的來源。 – martineau
感謝您的建議@馬蒂諾。 – user
它下載文件,但文件大小爲0 kb。 「0個文件成功下載」。 – user