使用python连接ftp 下载里面的文件 将下载的文件筛选出来然后再上传回来,先遇到的问题是 每天下载和上传回来的文件都对应的上,但是16号的文件无法下载下来 导致当天的文件没有筛选回传,求指导一下可以自动根据那天没有上传的文件 自动下载那天的文件,我现在使用的方法是下载每天前一天的方法
参考方案,最新代码,还望采纳:
import ftplib
import os
import time
ftp = ftplib.FTP("ftp.example.com")
ftp.login("username", "password")
def download_files(ftp, date):
# 切换到远程服务器的指定目录
ftp.cwd("/remote/directory")
# 获取当前目录下的文件列表
files = ftp.nlst()
for file_name in files:
# 判断文件是否是当天的文件
if date in file_name and file_name.endswith(".xlsx"):
# 下载文件
with open(file_name, "wb") as f:
ftp.retrbinary("RETR " + file_name, f.write)
# 进行筛选操作
# TODO: 筛选代码
# 获取当前的日期
today = time.strftime("%Y-%m-%d")
# 循环每天的日期
for i in range(11, 16):
date = f"2023-02-{i:02d}"
if date >= today:
break
download_files(ftp, date)
ftp.quit()
16.10
import ftplib
import os
# FTP 服务器地址和端口号
ftp_server = "ftp.example.com"
port = 21
# FTP 用户名和密码
username = "username"
password = "password"
# 指定 FTP 目录
ftp_dir = "/data"
# 本地下载目录
local_dir = "./download"
# 连接到 FTP 服务器
ftp = ftplib.FTP()
ftp.connect(ftp_server, port)
ftp.login(username, password)
ftp.cwd(ftp_dir)
# 获取 FTP 目录下的全部数据
ftp_files = ftp.nlst()
# 记录OLD文件的数量和RPA文件的数量
old_count = 0
rpa_count = 0
# 遍历 FTP 目录下的全部数据,统计OLD和RPA文件的数量
for file in ftp_files:
if file.startswith("OLD"):
old_count += 1
elif file.startswith("rpa"):
rpa_count += 1
# 如果OLD文件数量等于RPA文件数量,则不下载
if old_count == rpa_count:
print("OLD文件数量等于RPA文件数量,无需下载")
# 如果OLD文件数量少于RPA文件数量,则根据后面的日期20221227来判断RPA少那个,并下载OLD对应的文件
else:
for file in ftp_files:
if file.startswith("OLD"):
# 如果RPA文件不存在,则下载OLD对应的文件
rpa_file = file.replace("OLD", "rpa")
if rpa_file not in ftp_files:
local_file = os.path.join(local_dir, file)
with open(local_file, "wb") as f:
ftp.retrbinary("RETR " + file, f.write)
# 关闭连接
ftp.quit()
不知道你这个问题是否已经解决, 如果还没有解决的话: