【发布时间】:2021-12-15 10:48:27
【问题描述】:
该程序从urls.txt 文件中提供的链接下载文件,并假定python 脚本和urls.txt 位于同一文件夹中。如何更改程序以要求用户提供存储文件的路径并更新 urlretrieve 行?我怎样才能让程序打印正在下载的当前链接和正在下载的文件的名称?
import os.path
import urllib.request
links = open('urls.txt', 'r')
for link in links:
# Get one line of text (e.g. http://server/files/grades.doc),
# 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)
try:
urllib.request.urlretrieve(link, 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.")
【问题讨论】: