我当前正在使用以下代码下载某些csv文件:
import urllib
year = 2006
max_year = 2019
host = "http://data.wa.aemo.com.au/datafiles/outages/outages-"
ending = ".csv"
while year <= max_year:
url = host + str(year)+ending
print(url)
urllib.urlretrieve(url, url.lstrip(host))
print("Done")
year +=1
该脚本可以正常工作,但是它会下载具有非常通用名称的文件,就像:
2006
2007
2008
...
这可能会令人困惑。理想情况下,我希望脚本下载以下文件:
outages-2006
outages-2007
outages-2008
...
如何修改代码以实现所需的结果?
谢谢。
答案 0 :(得分:2)
您不知道“ lstrip”
点击此处https://www.tutorialspoint.com/python/string_lstrip.htm
使用此代码代替“ url.lstrip(host)”
# -*- coding: utf-8 -*-
from urllib.request import urlretrieve
year = 2006
max_year = 2019
host = "http://data.wa.aemo.com.au/datafiles/outages/outages-"
ending = ".csv"
while year <= max_year:
url = host + str(year) + ending
print(url)
file_name = "outages-" + str(year) + ending
print(file_name)
urlretrieve(url, file_name)
print("Done")
year += 1