我有下一个代码,它下载zip文件,但我只需要从ftp中修改或创建最后一个文件,而不是所有这些文件。
例如,我有:
在这种情况下,我只需要下载"one_20140222.xml.zip“文件。
有人能帮帮我吗?我刚开始使用蟒蛇。我下一步该怎么做?
#CODE
import ftplib
import os
import fnmatch
import datetime
from datetime import date, datetime, timedelta
ftp_server='ftp.blabla.com'
ftp_user='user'
ftp_pass='pass'
def download():
print 'dowloading from ftp server'
os.chdir('/root/dir/zip')
s = ftplib.FTP(ftp_server, ftp_user, ftp_pass)
s.cwd('one/two/')
fileList = s.nlst()
targetList = [fileName for fileName in fileList if fnmatch.fnmatch(fileName,'*.zip')]
if (targetList == []):
print 'No files to process'
for file in targetList:
print 'downloaded file: ' + file
try:
fileOut=open(file,'wb')
s.retrbinary('RETR '+file,fileOut.write)
fileOut.close()
except:
print 'Cant open file'
s.quit()发布于 2014-02-26 17:10:26
鉴于此,
filename1 = 'one_20140220.xml.zip'
filename2 = 'one_20140221.xml.zip'
file1 = filename1.split('.')[0].split('_')
file2 = filename2.split('.')[0].split('_')
print file1[1] < file2[1]
print file1[1], file2[1]
>>> True
>>> 20140220 20140221这应该可以让您进行比较检查。请注意,在这种情况下,您不必从字符串转换日期的值,因为字符串比较(年份、月、日)提供了正确的结果。
您可以设置一个字典,其中键为filex,值为所有filex1值的列表。然后循环遍历字典并选择最大值。
mydict ={filex[0]: [val1, val2, val3 ...], ... }
for f in mydict:
filename = f + max(mydict[f]) + '.xml.zip'
# Process the file name within a function
dofile(filename)发布于 2014-02-26 17:15:35
假设您的所有文件都在示例中命名,这非常简单。
import datetime
filenameFmt = "one_%Y%M%d.xml.zip" # You will need to update this to match the filenames
def getEarliestFile(arrayOfFiles):
namesWithDate = []
for filename in arrayOfFiles:
dt = datetime.datetime.strptime(filename,filenameFmt)
namesWithDate.append((filename,dt))
#sort the array in ascending order
namesWithDate = sorted(namesWithDate,key = lambda x: x[1])
#Grab and return the newest one
filename, dt = namesWithDate[-1]
return filename您可以将这个函数传递给所有文件名的完整列表,它返回最新文件名的文件名。
https://stackoverflow.com/questions/22048061
复制相似问题