Python 用多線程上傳和下載文件


 1 # -*- coding: utf-8 -*-
 2 __author__ = 'louis'
 3 
 4 from ftplib import FTP
 5 import multiprocessing
 6 import time
 7 
 8 
 9 def ftpconnect():
10     ftp = FTP()
11     timeout = 30
12     port = 22
13     ftp.connect('localhost',port,timeout) # 連接FTP服務器
14     ftp.login('user','password') # 登錄
15     return ftp
16 
17 def upload(FileName, FileLocalation):
18     ftp = ftpconnect()
19     # print ftp.getwelcome() # 獲得歡迎信息
20     ftp.cwd(r"") # 設置FTP路徑
21     for i in range(len(FileName)):
22         print "%s The start of upload, %s" % (time.ctime(),FileName[i])
23         fp = open(FileLocalation[i], 'rb')
24 
25         ftp.storbinary('STOR ' + FileName[i], fp)
26         fp.close()
27         print "%s The end of the %s" % (time.ctime(), FileName[i])
28     ftp.quit() # 退出FTP服務器
29 
30 def download(FileName, FilePath):
31     ftp = ftpconnect()
32     ftp.cwd(r"") # 設置FTP路徑
33     for i in range(len(FileName)):
34         print "%s The start of downloading, %s" % (time.ctime(), FileName[i])
35         file_handle = open(FilePath[i], 'w').write
36 
37         ftp.retrbinary("RETR " + FileName[i], file_handle)
38         print "%s The end of the %s" % (time.ctime(), FileName[i])
39 
40     ftp.quit()
41 
42 
43 if __name__=='__main__':
44     # 上傳視頻文件到服務器  前提是在c:\te中,已經有1000個視頻文件,它們的名字分別是1.avi, 2.avi. 3.avi, ..., 1000.avi
45     # p = [None]*1000
46     # filelocal = r'c:\Te'          
47     #
48     # for i in range(20):
49     #     baiWei = i * 50
50     #     filename = [None] * 50
51     #     filelocalation = [None] * 50
52     #     for j in range(50):
53     #         filename_pre = baiWei + j + 1
54     #         filename[j] = "%s.avi" % filename_pre
55     #         filelocalation[j] = filelocal + "\\" + filename[j]
56     #     print filelocalation
57     #     p[i] = multiprocessing.Process(target=upload, args=(filename, filelocalation))
58     #
59     # for i in range(20):
60     #     p[i].start()
61 
62 
63     # 下載視頻文件到本地,  前提是ftp服務器中已經有100個視頻文件,它們的名字是1.avi, 2.avi, 3.avi, ..., 100.avi
64     p = [None]*100
65     fileDir = r'D:\local'
66     for i in range(10):
67         shiWei = i * 10
68         fileName = [None]*10
69         filePath = [None]*10
70         for j in range(10):
71             fileName_pre = shiWei + j + 1
72             fileName[j] = "%s.avi" % fileName_pre
73             filePath[j] = fileDir + "\\" + fileName[j]
74         print filePath
75         p[i] = multiprocessing.Process(target=download, args=(fileName, filePath))
76 
77     for i in range(10):
78         p[i].start()
79     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM