python 下载文件到文件夹下的问题

#-*- coding:utf-8 -*-
import urllib2
re = urllib2.Request(r'http://www.google.cn/intl/zh-CN/images/logo_cn.gif')
rs = urllib2.urlopen(re).read()
open('google.gif', 'wb').write(rs)
这段代码是说把链接地址中现在下载下来的logo_cn.gif,以2进制的方式写到本地google.gif文件中吗?但我是用的爬虫循环好多下载地址,要怎么把它保存到本地磁盘的文件夹下(如:r'd:\download')

open文件的时候就可以设置文件的路径,比如,这里改成
open(r'd:\download\google.gif', 'wb').write(rs)
就保存到那个文件夹下了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-08-28
方法一:
import urllib
import urllib2
import requests
print "downloading with urllib"
url = 'http://www.pythontab.com/test/demo.zip'
print "downloading with urllib"
urllib.urlretrieve(url, "demo.zip")

方法二:
import urllib2
print "downloading with urllib2"
url = 'http://www.pythontab.com/test/demo.zip'
f = urllib2.urlopen(url)
data = f.read()
with open("demo2.zip", "wb") as code:
code.write(data)

方法三:
import requests
print "downloading with requests"
url = 'http://www.pythontab.com/test/demo.zip'
r = requests.get(url)
with open("demo3.zip", "wb") as code:
code.write(r.content)
第2个回答  2011-05-06
直接os.system('dir C:\Perl ')
或者 os.chdir(dirname) 改变当前工作目录
相似回答