Skip to content

Instantly share code, notes, and snippets.

@a37h
Last active May 26, 2021 05:13
Show Gist options
  • Save a37h/6dde2a1cb1548e13a3a4d3a0f03fca72 to your computer and use it in GitHub Desktop.
Save a37h/6dde2a1cb1548e13a3a4d3a0f03fca72 to your computer and use it in GitHub Desktop.
Download and save each file from a .txt document
from urllib.request import urlretrieve
import string
NAMES_WITH_LINKS_FILE_NAME = 'links-with-names.txt'
PATH_TO_SAVE = '/home/qua/Music/'
def get_name(name):
result = ''
for char in name:
if char.isalpha() or char.isdigit() or (char in string.punctuation):
result += char
else:
result += '?'
return result
# Some_File_-_Name_One
# https://example.com/some_file_name_one.zip
# Some_File_-_Name_Two
# https://example.com/some_file_name_two.mp3
with open(NAMES_WITH_LINKS_FILE_NAME, 'r') as f:
inputs = list(f)
n = len(inputs) // 2
print(f'Downloading files from "{NAMES_WITH_LINKS_FILE_NAME}" to "{PATH_TO_SAVE}"')
for i, even_odd in enumerate(zip(inputs[0::2], inputs[1::2])):
try:
name, link = even_odd[0].strip(), even_odd[1].strip()
name = get_name(name)
filename = name + '.mp3'
filepath = PATH_TO_SAVE + filename
print(f'> {i + 1}/{n} downloading "{name}"', end='', flush=True)
urlretrieve(link, filepath)
print(f' ---> done, saved as "{filename}"', flush=True)
except Exception as e:
print(f'[uncaught exception "{type(e)}" occured]')
with open('failed.txt', 'a') as f:
f.write(name + '\n')
f.write(link + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment