How can I download a file to a specific directory?

被刻印的时光 ゝ 提交于 2019-12-05 17:18:57

Sorry Guys I was Being stupid but to Answer the Question I added

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

right after the first if statement 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()

Pass the directory to open() in the filename.

Use os.path.join to add the directory to 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!