[英]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.