python使用ftplib上传下载文件
1.安装
python内置模块,不需要安装
2.使用
import ftplib
import os
class FTPTool:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
self.ftp = ftplib.FTP()
def connect(self):
self.ftp.connect(self.host)
self.ftp.login(self.username, self.password)
def disconnect(self):
self.ftp.quit()
def upload_file(self, local_file, remote_file):
"""上传文件"""
file_list = remote_file.split('/')
for file in file_list[1:-1]:
if file not in self.ftp.nlst():
self.ftp.mkd(file)
print('创建文件夹', file)
self.ftp.cwd(file)
else:
print('cd目录', file)
self.ftp.cwd(file)
with open(local_file, 'rb') as f:
self.ftp.storbinary('STOR ' + file_list[-1], f)
print('文件上传成功')
self.ftp.cwd('/')
def download_file(self, remote_file, local_file):
"""下载文件"""
os.makedirs(os.path.dirname(local_file), exist_ok=True)
with open(local_file, 'wb') as f:
self.ftp.retrbinary('RETR ' + remote_file, f.write)
def upload_folder(self, local_folder, remote_folder):
"""上传文件夹"""
for root, dirs, files in os.walk(local_folder):
for file in files:
local_file = os.path.join(root, file)
relpath = root.replace(local_folder, '')[1:]
remote_file = os.sep.join([remote_folder, relpath, file])
remote_file = remote_file.replace('\\', '/')
print(local_file, remote_file)
self.upload_file(local_file, remote_file)
def download_folder(self, remote_folder, local_folder):
"""下载文件夹"""
os.makedirs(local_folder, exist_ok=True)
self.ftp.cwd(remote_folder)
for file in self.ftp.nlst():
local_file = os.path.join(local_folder, file)
if self.is_directory(file):
self.download_folder(file, local_file)
else:
self.download_file(file, local_file)
self.ftp.cwd('..')
def is_directory(self, file_path):
try:
current_path = self.ftp.pwd()
self.ftp.cwd(file_path)
self.ftp.cwd(current_path)
return True
except ftplib.error_perm:
return False
if __name__ == '__main__':
ftp = FTPTool('192.168.1.3', 'username', 'password')
ftp.connect()
ftp.upload_file(local_file='./xxx/xxx/xxx.exe',
remote_file='/xxx/xxx/xxx/.exe')
ftp.download_folder('/xxx/xxx/xxx',
'./xxx')
ftp.disconnect()
3.编码错误
UnicodeEncodeError: ‘latin-1’ codec can’t encode characters in position 5-7: ordinal not in range(256)
更新python3.9版本解决