Python~FTP文件下载

通过Python 下载 FTP 服务器上的文件

环境 Python3.7
import os
from ftplib import FTP

# 环境 Python 3.7
# 根据实际环境需要修改的变量:host,username,password,localpath,ftppath

# 1.登录FTP服务器
host = '192.168.131.154'
ftp = FTP()
ftp.connect(host, 21)
useranme = 'test'
password = 'test@123'
ftp.login(useranme,password)

# 2.切换到FTP服务器下载文件的路径
ftppath = '/DOC/'
ftp.cwd(ftppath)
# 切换到FTP服务器的路径下

# 3.获取FTP服务器切换路径下的文件名,定义为一个filebefore列表
filebefore = ftp.nlst()
# ftp.nlst()获取FTP服务器/DOC/路径下的文件名
# 将获取到的文件名放在列表里面

# 4.切换本地存放的路径
localpath = 'D:\\Documents\\'
os.chdir(localpath)
# 切换到本地目录下

# 5.判断部分文件是否存在
fileafter = []
# 定义一个空列表,通过获取到的文件名,判断是文件是否存在。
# 如果不存在,将不存在的文件名添加到fileafter列表里。
# 判断文件
for fileone in filebefore:
    if not os.path.exists(fileone):
        fileafter.append(fileone)

# 6.下载fileafter列表里的文件
for filetwo in fileafter:
    file_handle = open(filetwo, 'wb').write
    ftp.retrbinary('RETR %s' % filetwo, file_handle, blocksize=1024)
ftp.quit()

# 7.查看本地目录下载后的文件名
print(os.listdir())

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值