python使用ftplib上传下载文件

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版本解决

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值