如何将文件下载到特定目录?

时间:2012-03-09 04:04:48

标签: python download dir

我最近一直试图在python中创建一个将文件下载到特定目录的程序。我正在使用Ubuntu,到目前为止我有这个

import os
import getpass
import urllib2

y = getpass.getuser()

if not os.access('/home/' + y + '/newdir/', os.F_OK):
    print("Making New Directory")
    os.mkdir('/home/' + y + '/newdir/')

url = ("http://example.com/Examplefile.ex")
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
    break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

目前将文件下载到同一目录,如何更改下载的目录?

修复了新代码:

import os
import getpass
import urllib2

y = getpass.getuser()

if not os.access('/home/' + y + '/newdir/', os.F_OK):
    print("Making New Directory")
    os.mkdir('/home/' + y + '/newdir/')

os.chdir('/home/'+y+'/newdir/')

url = ("http://example.com/Examplefile.ex")
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
    break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

3 个答案:

答案 0 :(得分:2)

对不起伙计我是傻了但回答了我添加的问题

os.chdir('/home/' + y + '/newdir/')

在第一个if语句ex:

之后
import os
import getpass
import urllib2

y = getpass.getuser()

if not os.access('/home/' + y + '/newdir/', os.F_OK):
    print("Making New Directory")
    os.mkdir('/home/' + y + '/newdir/')

os.chdir('/home/'+y+'/newdir/')

url = ("http://example.com/Examplefile.ex")
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
    break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

答案 1 :(得分:0)

将目录传递给文件名中的open()

答案 2 :(得分:0)

使用os.path.join将目录添加到file_name

    from os.path import join

    directory = join('/home/', y, '/newdir/')
    # You can now use directory everywhere you used to build the directory name

    # and then, later in the script:
    file_name = url.split('/')[-1]
    file_name = join(directory, file_name)