我正在使用 urllib.urlretrieve
下载文件,我想添加一些内容以在下载前检查更改。我已经有如下内容:
import urllib
urllib.urlretrieve("http://www.site1.com/file.txt", r"output/file1.txt")
urllib.urlretrieve("http://www.site2.com/file.txt", r"output/file2.txt")
理想情况下,我希望脚本检查更改(比较上次修改的标记?),如果相同则忽略,如果更新则下载,我需要脚本为文件名添加时间戳。
有人能帮忙吗?
我是编程新手(python 是我的第一个)所以欢迎任何批评!
最佳答案
不幸的是,这在 Python 中似乎很难做到,因为您必须自己做所有事情。此外,urlretrieve
的界面不是很好。
以下代码应执行必要的步骤(如果文件存在则添加“If-Modified-Since” header 并调整下载文件的时间戳):
def download_file(url, local_filename):
opener = urllib.request.build_opener()
if os.path.isfile(local_filename):
timestamp = os.path.getmtime(local_filename)
timestr = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timestamp))
opener.addheaders.append(("If-Modified-Since", timestr))
urllib.request.install_opener(opener)
try:
local_filename, headers = urllib.request.urlretrieve(url, local_filename, reporthook=status_callback)
if 'Last-Modified' in headers:
mtime = calendar.timegm(time.strptime(headers['Last-Modified'], '%a, %d %b %Y %H:%M:%S GMT'))
os.utime(local_filename, (mtime, mtime))
except urllib.error.HTTPError as e:
if e.code != 304:
raise e
urllib.request.install_opener(urllib.request.build_opener()) # Reset opener
return local_filename
关于python - 为使用 urllib.urlretrieve 下载的文件添加时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16650608/