2.3 利用FTP服务器下载和上传文件

时间:2021-11-22 18:10:09

二.利用FTP服务器的下载文件

from ftplib import FTP
from os.path import exists

def getfile(file,site,dir,user=(),*,verbose=True,refetch=False): #verbose为是否打印信息,refetch为是否重新获取文件
if exists(file) and not refetch:
if verbose: print(file,'already fetched')
else:
if verbose:print('Downloading',file)
local
= open(file,'wb')
try:
remote
= FTP(site)
remote.login(
*user)
remote.cwd(dir)
remote.retrbinary(
'RETR ' + file, local.write, 1024)
remote.quit()
if verbose: print('Finished')
finally:
local.close()


if __name__ == '__main__':
file
= 'new_1.py'
dir
= '.'
site
= '192.168.191.1'
user
= ()
getfile(file,site,dir,user)

 

二.利用FTP服务器的上传文件

import ftplib

def putfile(file,site,dir,user=(),*,verbose=True):
if verbose: print('Uploading',file)
local
= open(file,'rb')
remote
= ftplib.FTP(site)
remote.login(
*user)
remote.cwd(dir)
remote.storbinary(
'STOR ' + file,local,1024)
remote.quit()
local.close()
if verbose: print('Upload done')

if __name__ == '__main__':
file
= 'test.py'
dir
= '.'
site
= '192.168.191.1'
user
= ()
putfile(file, site, dir, user)