python连接ftp服务器 下载整个目录 ftp删除目录 删除文件 下载单个文件 ftp 上传目录

337 篇文章 3 订阅
44 篇文章 1 订阅

2023年4月27日 星期四 更新

上传目录

import ftplib
import os

def upload_directory(ftp, local_path, remote_path):
    """
    上传本地目录到FTP服务器
    """
    if not os.path.isdir(local_path):
        raise ValueError(f"本地路径 {local_path} 不是一个目录")
    try:
        ftp.cwd(remote_path)
    except ftplib.error_perm:
        # 远程路径不存在,需要创建
        ftp.mkd(remote_path)
        ftp.cwd(remote_path)
    for name in os.listdir(local_path):
        local_pathname = os.path.join(local_path, name)
        if os.path.isdir(local_pathname):
            upload_directory(ftp, local_pathname, os.path.join(remote_path, name))
        else:
            with open(local_pathname, "rb") as file:
                ftp.storbinary(f"STOR {name}", file)

# 连接到 FTP 服务器
ftp = ftplib.FTP("ftp.example.com")
ftp.login("username", "password")

# 调用函数上传目录
local_path = "/path/to/local/directory"
remote_path = "/path/to/remote/directory"
upload_directory(ftp, local_path, remote_path)

# 关闭 FTP 连接
ftp.quit()

下载单个文件

            with open(file_name, 'wb') as f:
                ftp.retrbinary('RETR ' + i, f.write)
                print('download success --> ', i)

参考
https://stackoverflow.com/questions/11573817/how-to-download-a-file-via-ftp-with-python-ftplib

	import ftplib
	
	host='192.168.11.50'
	f=ftplib.FTP()
	f.encoding = 'GB18030'
	f.connect(host,21001)
	f.login('ftpuser','XXXXXXXXXXX')       
	
	print("FTP服务器已经成功登录")
	f.dir()
	print('当前工作目录:',f.pwd())
	f.cwd("音乐")
	
	upload_file="/home/hp/文档/音乐/再度重相逢.ape"
	ff=open(upload_file,'rb')
	print(f.storbinary("STOR 再度重相逢.ape",ff))
	
	f.quit()
	print("FTP服务器已断开")

from ctypes import *
import os
import sys
import ftplib
import time
import tempfile
import win32api
import win32print

class myFtp:
    ftp = ftplib.FTP()
    def __init__(self, host, port=21):
        self.ftp.connect(host, port)
        self.ftp.encoding = 'gbk'

    def Login(self, user, passwd):
        self.ftp.login(user, passwd)
        print(self.ftp.welcome)

    def DownLoadFile(self, LocalFile, RemoteFile):  # 下载单个文件
        file_handler = open(LocalFile, 'wb')
        #print(file_handler)
        # self.ftp.retrbinary("RETR %s" % (RemoteFile), file_handler.write)#接收服务器上文件并写入本地文件
        self.ftp.retrbinary('RETR ' + RemoteFile, file_handler.write)
        file_handler.close()
        return True

    def DownLoadFileTree(self, LocalDir, RemoteDir):  # 下载整个目录下的文件
        print("远程文件夹remoteDir:", RemoteDir)
        if not os.path.exists(LocalDir):
            os.makedirs(LocalDir)
        self.ftp.cwd(RemoteDir)
        RemoteNames = self.ftp.nlst()
        print("远程文件目录:", RemoteNames)
        for file in RemoteNames:
            Local = os.path.join(LocalDir, file)
            print("正在下载", self.ftp.nlst(file))
            if file.find(".") == -1:
                if not os.path.exists(Local):
                    os.makedirs(Local)
                self.DownLoadFileTree(Local, file)
            else:
                self.DownLoadFile(Local, file)
        self.ftp.cwd("..")
        return

    def close(self):
        self.ftp.quit()


if __name__ == "__main__":
    ftp = myFtp('IP')
    ftp.Login('账户', '密码')
    data = str(time.strftime("%m%d"))
    local_path = 'D:/文件夹/'+data
    romte_path = '/文件夹/'+data
    ftp.DownLoadFileTree(local_path,romte_path)  # 从目标目录下载到本地目录d盘
    ftp.close()
    print("下载完成")

https://blog.csdn.net/gc_2299/article/details/123674840

https://zhuanlan.zhihu.com/p/221911477

删除参考
https://stackoverflow.com/questions/10042838/delete-all-files-and-folders-after-connecting-to-ftp

https://stackoverflow.com/questions/24738932/delete-files-from-ftp-after-download

remove dir example
https://python.hotexamples.com/zh/examples/ftplib/FTP/delete/python-ftp-delete-method-examples.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值