【发布时间】:2017-01-14 10:40:29
【问题描述】:
我一直在尝试用 Python 编写一个函数,允许下载最近添加的文件(通过文件名中的时间戳)。
你可以看到格式有一个很大的时间戳。
到目前为止,我在论坛的帮助下得到了以下代码。 在以下代码中,我尝试使用日期字段(实际添加到 FTP 服务器的日期)进行排序。然而, 我想调整这段代码,以便我可以按文件名中的时间戳对文件进行排序。
EDIT(尝试清理一下代码):
def DownloadFileFromFTPServer2 (server, username, password, directory_to_file, file_to_write):
try:
f = ftplib.FTP(server)
except ((socket.error, socket.gaierror), e):
print ('cannot reach to %s' % server)
return
print ("Connected to FTP server")
try:
f.login(username, password)
except ftplib.error_perm:
print ("cannot login anonymously")
f.quit()
return
print ("Logged on to the FTP server")
try:
f.cwd(directory_to_file)
print ("Directory has been set")
except Exception as inst:
print (inst)
data = []
f.dir(data.append)
datelist = []
filelist =[]
for line in data:
print (line)
col = line.split()
datestr = ' '.join(line.split()[5:8])
date = time.strptime (datestr, '%b %d %H:%M')
datelist.append(date)
filelist.append(col[8])
combo = zip (datelist, filelist)
who = dict ( combo )
# Sort by dates and get the latest file by date....
for key in sorted(iter(who.keys()), reverse = True):
filename = who[key]
print ("File to download is %s" % filename)
try:
f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
except (ftplib.err_perm):
print ("Error: cannot read file %s" % filename)
os.unlink(filename)
else:
print ("***Downloaded*** %s " % filename)
print ("Retrieving FTP server data ......... DONE")
#VERY IMPORTANT RETURN
return
f.quit()
return 1
非常感谢任何帮助。谢谢。
编辑 [已解决]:
线
date = time.strptime (datestr, '%b %d %H:%M')
应替换为:
try:
date = datetime.datetime.strptime (str(col[8]), 'S01375T-%Y-%m-%d-%H-%M-%S.csv')
except Exception as inst:
continue
try-continue 很重要,因为前两条路径行,例如 '.'和 '..' 将导致 ValuError。
【问题讨论】:
-
我们不需要所有的 FTP 代码。 minimal reproducible example 将包括输入列表和预期结果(输出列表/项目)。剩下的只是污染。
-
我同意。对不起,混乱。会尝试清理它
-
如果所有文件都以
S01375T-开头,然后获取全名并对其进行排序——它们应该按照您的预期排序。如果它们以不同的文本开头但长度为 sam,则使用切片"S01375T-2016-12-01-10-59-03.csv"[8:-4]->"2016-12-01-10-59-03"并对这些字符串进行排序,它们应该按照您的预期排序。 -
如果名称以不同长度的文本开头,但首先
-总是在年份之前,然后使用split('-',1)-"S01375T-2016-12-01-10-59-03.csv".split('-', 1)[1]->'2016-12-01-10-59-03.csv'并对这些字符串进行排序
标签: python python-3.x sorting urllib ftplib