-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadThread.py
More file actions
57 lines (43 loc) · 1.83 KB
/
DownloadThread.py
File metadata and controls
57 lines (43 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import urllib.request
import time
from threading import Thread
destination_folder = "flamingos_files"
class DownloadThread(Thread):
# set up the __init__ to accept a url and a name for the thread
def __init__(self, url, name):
Thread.__init__(self)
self.name = name
self.url = url
print("%s: %s - starting" % (self.name, time.ctime(time.time())))
# run the thread - open up the url, extract the filename
# and then use that filename for naming / creating the file on disk
def run(self):
# urllib is used to do the actual downloading inside the thread class
handle_remote = urllib.request.urlopen(self.url)
# The os module is used to extract the name of the downloading file,
# so it's used to create a file with the same name on our machine.
file_name = os.path.basename(self.url)
# download the file a kilobyte at a time and write it to disk
with open(file_name, "wb") as file_handler:
while True:
part = handle_remote.read(1024)
if not part:
break
file_handler.write(part)
print("%s: %s - ending" % (self.name, time.ctime(time.time())))
# open the file with the images URLs, read them and close the file
my_file = open("source_files.txt", "r")
urls = my_file.readlines()
my_file.close()
# create and change working directory
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
os.chdir(destination_folder)
if __name__ == "__main__":
# initiate download of all described images in separate threads
# for index, image_url in enumerate(urls):
for index, image_url in enumerate(urls):
thread_name = "Thread %s" % (index + 1)
thread = DownloadThread(image_url.strip(), thread_name)
thread.start()