如何在urlretrieve中使用变量代替目标文件

时间:2019-02-19 10:09:12

标签: python urllib

我没有得到正确的结果

使用各种变量值运行代码

import urllib.request
x=input("enter the source link") # from where the file is to be downloaded
y=input("enter the destination address") # where the file is to be saved
z=input("enter file name") # the name by which you wish to save
s=input("enter extension type") # the extension of the file
url = x  # from where the file is to be downloaded
urllib.request.urlretrieve(url, 'y/z.s') # using variables to write the destination 

print('Beginning file download') # ensure success of above code

由于目标文件夹中的第7行,我的输出出现错误

以下错误


FileNotFoundError                         Traceback (most recent call last)
<ipython-input-2-f187f3520048> in <module>
      5 s=input("enter extension type") # the extension of the file
      6 url = x  # from where the file is to be downloaded
----> 7 urllib.request.urlretrieve(url, 'y/z.s') # using variables to write the destination
      8 
      9 print('Beginning file download') # ensure success of above code

C:\ProgramData\Anaconda3\lib\urllib\request.py in urlretrieve(url, filename, reporthook, data)
    255         # Handle temporary file setup.
    256         if filename:
--> 257             tfp = open(filename, 'wb')
    258         else:
    259             tfp = tempfile.NamedTemporaryFile(delete=False)

FileNotFoundError: [Errno 2] No such file or directory: 'y/z.s'

请指导

2 个答案:

答案 0 :(得分:0)

您以与其他任何字符串相同的方式使用它们;通过串联或插值。

'{}/{}.{}'.format(y, z, s)

f'{y}/{z}.{s}

y + '/' + z + '.' + s

答案 1 :(得分:0)

f'{x}:{y}'

对concat str使用格式。 或直接使用+运算符。