下面我列出了當前的代碼,我列出了整個文件夾,運行文件並下載它們。但是,此方法不支持遍歷子文件夾和文件夾。遍歷文件夾和子文件夾以獲取每個目錄中的文件FTP Python
def handleDownload(block):
file.write(block)
ddir='U:/Test Folder'
filedestination = 'U:/SWEModelConstruction/UnmaskedData'
t1= []
t2= []
t3= []
os.chdir(ddir)
ftp = FTP('sidads.colorado.edu')
ftp.login()
print ('Logging in.')
directory = '/pub/DATASETS/NOAA/G02158/unmasked/'
print ('Changing to ' + directory)
ftp.cwd(directory)
ftp.retrlines('LIST')
print ('Accessing files')
filenames = ftp.nlst() # get filenames within the directory
print (filenames)
for filename in filenames:
if filename not in ['.', '..']:
#Parse values from filename to use in os.path.join
for fname in filenames:
t1 = fname[16:20]
t2 = fname[20:22]
t3 = fname[22:24]
t4 = fname[16:24]
if not t1: continue
#use parsed values from filenamee to create folder and file pathss
local_folder = os.path.join(filedestination, t1,t2,t3)
local_filename = os.path.join(filedestination, t1,t2,t3,filename)
local_dat = os.path.join(filedestination, t1,t2,t3,'zz_ssmv11034tS__T0001TTNATS'+t4+'05HP001.dat.gz')
local_hdr = os.path.join(filedestination, t1,t2,t3,'zz_ssmv11034tS__T0001TTNATS'+t4+'05HP001.Hdr.gz')
hdrfile = ('zz_ssmv11034tS__T0001TTNATS'+t4+'05HP001.Hdr')
print (local_folder)
print (local_filename)
#check if folder for file exists and wether or not you have already it
if os.path.exists(local_folder) and not os.path.isfile(local_filename):
with open(local_filename, 'wb') as f_output:
ftp.retrbinary('RETR '+ filename, f_output.write)
ftp.quit()
做一個函數,每次你找到一個目錄時遞歸調用自己 –