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

标签 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()

最佳答案

对不起伙计们,我是愚蠢的,但要回答我添加的问题

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

紧接在第一个 if 语句之后:

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()

关于python - 如何将文件下载到特定目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628770/

相关文章:

python - 我们可以在位置格式化中执行算术运算吗?

python - pandas 版本的 SQL CROSS APPLY

python - 尝试将 SQL 查询转换为 SQLAlchemy 查询

PHP 强制下载远程文件

javascript - 相当于 Javascript 中的 Python 目录

python - 从图像中提取时钟指针

Java:下载url中含有特殊字符的网页内容

java - 在文件下载中实现暂停/恢复

regex - 查找文件夹中编号最大的文件名

c - 获取没有完整路径的目录名 (C unix)