Need Help
Get input for where the file is located & tell the new directory to save downloaded URLs to filepath variable assumes the text document with links is in the location of the python script - while this works, I would also like this to change to direct.
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."
If your error is concerning why the newpath
doesn't seem to connect to it. This is because I believe, in this line of code urllib.request.urlretrieve(link, newpath + filename)
, the link
param doesn't represent anything. You may try and print that value and see what it prints.
Note that link
in the for loop is a local variable, and anything saved in there will not be accessible anywhere else in the code.
for link in links:`
# then get the filename from the end of the URL
link = link.strip()
filename = link.rsplit('/', 1)[-1]
Try defining a global variable named link
outside the loop so that the value saved in the loop can be preserved to be used everywhere in the code. Like so,
filepath = input('please input the url file path: ')
links = open('links.txt', 'r')
newpath = input('Where would you like to store the file? ')
link = ""
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.