[英]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.