[英]download from path 'file' save to 'other directory' python script issue
需要帮忙
获取文件所在位置的输入并告诉新目录将下载的 URL 保存到 filepath 变量假定带有链接的文本文档位于 python 脚本的位置 - 虽然这有效,但我也希望将其更改为直接。
import os.path
import urllib.request
# Get one line of text (e.g. C:\user\user\path\directory)
filepath = input('please input the url file path: ')
links = open('links.txt', 'r')
newpath = input('Where would you like to store the file? ')
for link in links:`
# then get the filename from the end of the URL
link = link.strip()
filename = link.rsplit('/', 1)[-1]
# Does this file exist in this folder? If not, download it
if not (os.path.isfile(filename)):
print ('Downloading: ' + filename + " to " + newpath)
try:
urllib.request.urlretrieve(link, newpath + filename)
print ("File size was", os.path.getsize(filename))
except Exception as inst:
print (inst)
print (' Encountered unknown error. Continuing.')
# File exists; don't download
else:
print("This file exists already.")
# End of program
print("Finished downloading."
如果您的错误是关于为什么newpath
似乎没有连接到它。 这是因为我相信,在这行代码urllib.request.urlretrieve(link, newpath + filename)
, link
参数不代表任何东西。 您可以尝试打印该值并查看它打印的内容。
请注意,for 循环中的link
是一个局部变量,保存在那里的任何内容都无法在代码的其他任何地方访问。
for link in links:`
# then get the filename from the end of the URL
link = link.strip()
filename = link.rsplit('/', 1)[-1]
尝试在循环外定义一个名为link
的全局变量,这样循环中保存的值就可以保留下来,以便在代码中的任何地方使用。 像这样,
filepath = input('please input the url file path: ')
links = open('links.txt', 'r')
newpath = input('Where would you like to store the file? ')
link = ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.