1
我试图实现一个python脚本,它将比较本地和远程托管文件的最后修改日期。Python - 比较两个文件的最后修改日期,本地和远程
如果远程文件更新它应该: - 删除本地文件 - 下载远程文件与上次修改日期不变
最接近的答案我发现这是Last Modified of file downloaded does not match its HTTP header,但是我相信这下载整个文件,所以没有节省太多的资源/时间
我想要做的只是审查远程文件的头,而不是下载整个文件,我相信应该更快。
这是我目前的代码,这是非常混乱和noobish(见字符串替换等)我敢肯定有一个更好/更快的方式 - 你可以建议?
remote_source = 'http://example.com/somefile.xml'
local_source = 'path/to/myfile.xml'
if path.exists(local_source):
local_source_last_modified = os.path.getmtime(local_source)
local_source_last_modified = datetime.datetime.fromtimestamp(local_source_last_modified).strftime('(%Y, %m, %d, %H, %M, %S)')
conn = urllib.urlopen(remote_source)
remote_source_last_modified = conn.info().getdate('last-modified')
remote_source_last_modified = str(remote_source_last_modified)
remote_source_last_modified = remote_source_last_modified.replace(", 0, 1, 0)", ")")
if local_source_last_modified < remote_source_last_modified:
pass
else:
headers = urlretrieve(remote_source, local_source)[1]
lmStr = headers.getheader("Last-Modified")
remote_source_last_modified = mktime(strptime(lmStr, "%a, %d %b %Y %H:%M:%S GMT"))
os.utime(local_source, (remote_source_last_modified, remote_source_last_modified))
else:
headers = urlretrieve(remote_source, local_source)[1]
lmStr = headers.getheader("Last-Modified")
remote_source_last_modified = mktime(strptime(lmStr, "%a, %d %b %Y %H:%M:%S GMT"))
os.utime(local_source, (remote_source_last_modified, remote_source_last_modified))