如何在 python 中創建一個腳本,通過用戶通過控制臺在輸入中輸入的值,在存盤庫的特定 url 中替換,以便能夠下載 .zip,并且當它自動下載時,一個檔案夾在輸入的地方創建并解包,例如:
給定兩個隨機的 github url:
https://github.com/exercism/python/archive/refs/heads/bobahop-patch-1.zip
https://github.com/exercism/python/archive/refs/heads/bobahop-patch-2.zip
用戶可以通過控制臺輸入“patch-1”或“patch-2”,這個值將在 url 中替換,然后鏈接將被執行,并且它包含的 .zip 將被下載到存盤庫。同時,將創建一個具有任何名稱的檔案夾(例如,用戶在控制臺中輸入的值)并將下載的 .zip 移動到該檔案夾??,然后將其解壓縮。
uj5u.com熱心網友回復:
Python有
urllib從網頁獲取/下載資料的標準模塊urllib.request.urlretrieve()os創建檔案夾os.makedirs()和移動/重命名檔案的標準模塊os.rename()zipfile壓縮/解壓縮.zip檔案的標準模塊
import os
import urllib.request
import zipfile
#user_input = input("What to download: ")
user_input = 'patch-1'
pattern = 'https://github.com/exercism/python/archive/refs/heads/bobahop-{}.zip'
url = pattern.format(user_input)
filename = f"{user_input}.zip"
print('From:', url)
print(' To:', filename)
urllib.request.urlretrieve(url, filename)
# ---
destination_folder = user_input
print('Create folder:', destination_folder)
os.makedirs(destination_folder, exist_ok=True)
# ---
print('Uncompress')
zip_file = zipfile.ZipFile(filename)
zip_file.extractall(destination_folder)
# ---
print("Move .zip to folder")
old_name = filename
new_name = os.path.join(destination_folder, filename)
os.rename(old_name, new_name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/484418.html
下一篇:設定乳膠變數并重用它
