![](/img/trans.png)
[英]Using Python, how to download multiple files from a subdirectory on FTP server into a desired directory on local machine?
[英]Download directory/files from FTP location using python script
下載無法在python中工作?
我編寫了一個簡單的python程序,以從FTP位置獲取文件,但是當我執行它時,它會顯示錯誤[Errno 13]權限被拒絕的消息。
我的代碼如下。 知道為什么它不起作用嗎?
import ftplib
from ftplib import FTP, error_perm
def getFTPDir(dirpath):
f = ftplib.FTP(ip, username, password)
try:
f.cwd(dirpath)
nameList = f.nlst()
oldest = nameList[0]
newest = nameList[-1]
newest = oldest
newDirPath = dirpath +'/'+ newest
print f.cwd(newDirPath)
subNameList = f.nlst()
for i in range (len(subNameList)):
f.cwd( newDirPath + '/' + str(subNameList[i]) )
nameList1 = f.nlst()
filename = nameList1[i]
print "downloading..............", filename
f.retrbinary('RETR '+ filename, open(os.path.join(destination,localPath),"wb").write)
print filename + " downloaded"
try:
fhandle = open(filename, 'wb')
f.retrbinary('RETR ' + filename, fhandle.write)
except Exception, e:
print str(e)
finally:
fhandle.close()
except error_perm:
return
except Exception, e:
print str(e)
finally:
f.close()
ftplib的文檔說(強調我的):
FTP.retrbinary(command,callback [,maxblocksize [,rest]])
以二進制傳輸模式檢索文件。 該命令應為適當的RETR命令:“ RETR文件名”。 對於每個接收到的數據塊 , 將調用回調函數 ,並使用單個字符串參數指定該數據塊。
因此,這里有2種可能的錯誤原因:
destination
和localPath
可能指向不存在的文件夾或不可寫的文件夾或文件(順便說一句,您將在每次迭代中重寫相同的文件...) 不要這樣做,而是繼續做您在下一行寫的內容,或者甚至更好地使用with:
try:
localname = os.path.join(destination,localPath)
# a spy to control the names, comment it out when it works
print filename, " -> ", localname
with open(localname, 'wb') as fhandle
f.retrbinary('RETR ' + filename, fhandle.write)
except Exception as e:
print str(e)
這樣一來,您就可以看到在哪里寫東西...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.