2016-07-31 89 views
1

嘗試將我的第一個有用的Python程序放在一起,目的是自動執行我的網站備份。我看了一篇關於如何下載單個文件的教程,但是當涉及到一個文件夾時,我不太清楚。我想通過FTP從我的網站創建一個完整文件夾的本地備份。使用Python通過FTP下載整個目錄

到目前爲止,我想出了這一點,有一些幫助從this question

from ftplib import FTP 
import os 

ftp=FTP("ftp.xxxxxxxxx.com") 
ftp.login("xxxxxxxxxxx","xxxxxxxxxx") #login to FTP account 
print "Successfully logged in" 
ftp.cwd("public_html") #change working directory to \public_html\ 
filenames = ftp.nlst() #create variable to store contents of \public_html\ 

os.makedirs("C:\\Users\\xxxxxx\\Desktop\\Backup")#create local backup directory 
os.chdir("C:\\Users\\xxxxxx\\Desktop\\Backup")#change working directory to local backup directory 

#for loop to download each file individually 
for a in filenames: 
    ftp.retrbinary("RETR " + a, file.write) 
    file.close() 


ftp.close() #CLOSE THE FTP CONNECTION 
print "FTP connection closed. Goodbye" 

我不願意運行它,因爲我不想在我的網站上創建一個問題,如果它是錯的。我應該注意到,本地文件的擴展名&應該與正在下載的遠程文件的文件名完全匹配。

任何指導讚賞!

+0

的可能的複製[下載一個目錄樹與FTPLIB](http://stackoverflow.com/questions/2605119/downloading-a-directory-tree-with-ftplib) –

回答

2

您不需要更改工作目錄,只需將文件保存在預期路徑中即可。

而對於下載文件,您首先需要獲取文件名列表:

file_list = [] 
ftp.retrlines('LIST', lambda x: file_list.append(x.split())) 

然後將文件分開,通過目錄,並下載:

for info in file_list: 
    ls_type, name = info[0], info[-1] 
    if not ls_type.startswith('d'): 
     with open(name, 'wb') as f: 
      ftp.retrbinary('RETR {}'.format(f), f.write) 
+1

在最後一行,'ftp.retrbinary('RETR {}'。fromat(f ),f.write)'我想你的意思是'.format(f)'而不是'fromat(f)' – theeastcoastwest

+0

@Frank是的,謝謝fo r評論。 – Kasramvd