我编写了一个类,它从 ftp 站点(ftp://ladsweb.nascom.nasa.gov/allData/5/MOD11A1/)下载一个文件,在调用类实例时给定部分文件名。后来我写了一个for循环并将类实例集成到for循环中,这样我就可以下载多个日期范围内的文件。这是一个日期范围,因为文件是根据它们的生成日期命名的。所以每天都有文件。当您运行代码时,系统会要求您输入日期范围。该范围的第一个文件已成功下载,但是当程序停止并打印以下错误时:
Traceback (most recent call last):
File "ftplib04Simplified.py", line 42, in <module>
FtpDownloader("ladsweb.nascom.nasa.gov","/allData/5/MOD11A1/",a).findFile(10,11)
File "ftplib04Simplified.py", line 32, in findFile
self.ftp.retrbinary('RETR %s' % filename, open(filename,'wb').write)
File "/usr/lib/python3.3/ftplib.py", line 424, in retrbinary
with self.transfercmd(cmd, rest) as conn:
File "/usr/lib/python3.3/ftplib.py", line 386, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/usr/lib/python3.3/ftplib.py", line 352, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib/python3.3/ftplib.py", line 259, in sendcmd
return self.getresp()
File "/usr/lib/python3.3/ftplib.py", line 233, in getresp
raise error_perm(resp)
ftplib.error_perm: 550 No such file.
shell returned 1
我知道纯类设计会让我感到羞耻,但这是我编写的完整代码: PS 这是用 Python 3 编写的。如果运行代码,当要求输入时,请输入 2001 年之后的日期。
import ftplib
import math
import datetime as dt
import time
class FtpDownloader:
"""Downloads raster tiles given the date, and tile row and column number"""
def __init__(self,site,directory,raw_date,ftp=None):
"""logs in to ftp"""
self.site=site
self.directory=directory
self.raw_date=raw_date
self.ftp=ftplib.FTP(site)
self.ftp.login()
self.convert_date()
def convert_date(self):
"""converts YYYY-MM-DD format to year and day of the year"""
year=self.raw_date.strftime("%Y")
day=self.raw_date.strftime("%j")
self.go_to_folder(year,day)
def go_to_folder(self,year,day):
"""sets the current FTP directory"""
self.ftp.cwd(self.directory+"%s/%s/" % (year,day))
def findFile(self,h,v,fileList=[]):
"""checks for the file containing the given h and h and downloads it using retrbinary"""
hh= "%02d" % h
vv= "%02d" % v
tilename = "h%sv%s" % (hh,vv)
print ("Image tile %s is downloading..." % tilename)
self.ftp.retrlines('NLST',fileList.append)
for filename in fileList:
if tilename in filename:
self.ftp.retrbinary('RETR %s' % filename, open(filename,'wb').write)
print ("File downloaded")
break
else:
print (filename, "not found")
self.ftp.close()
start=dt.datetime.strptime(input("Enter a start date in YYYY-MM-DD format "),"%Y-%m-%d")
end=dt.datetime.strptime(input("Enter an end date in YYYY-MM-DD format "),"%Y-%m-%d")
for i in range((end-start).days + 1):
a=(start+dt.timedelta(days=i)).date()
FtpDownloader("ladsweb.nascom.nasa.gov","/allData/5/MOD11A1/",a).findFile(10,11)