【问题标题】:how to retrieve the latest file from an ftp folder using Python? [duplicate]如何使用 Python 从 ftp 文件夹中检索最新文件? [复制]
【发布时间】:2013-03-26 14:46:50
【问题描述】:

在我的公司,我们有一个秤,可以在将箱子装入卡车之前检查它们的重量。如果盒子包含的产品多于或少于可接受的产品,则该盒子将被拒绝并传送到另一条传送带。电子秤记录操作的执行情况。文件存储在秤的磁盘中,并使用 ftp 从附近的台式计算机进行访问。我的老板希望报告自动通过电子邮件发送到他的帐户,这样他就不需要去那个设施检查前一天的拒绝情况。我开始用 Python 编写一个程序来做到这一点,但被困在从文件夹中检索文件的部分。这是我的代码:

#This program tries to retrieve the latest report and send it by email.
import urllib
import shutil
import ftplib
import os
import sys
import glob
import time
import datetime
import smtplib
import email

#Define the server and folder where the reports are stored.
carpetaftp = "/reports/"

#This function looks for the last file in the folder.
def obtenerultimoarchivo(camino):
    for cur_path, dirnames, filenames in os.walk(camino):
        for filename in filenames:
            datos_archivo = os.stat(filename)
            tiempo_archivo = datos_archivo.st_mtime

#Connects to an ftp folder and downloads the last report.
def descargareporteftp(carpetaftp):
    ftp = ftplib.FTP("server.scale.com")
    ftp.login()
    ftp.cwd(carpetaftp)
    #Uses 'ultimoreporte.pdf' as a copy of the last report.
    archivo = open('C:\\Balanza\\Reportes\\ultimoreporte.pdf',"wb")
    ftp.retrbinary("RETR " + obtenerultimoarchivo(),archivo.write)
    archivo.close()
    return archivo

#The function enviaemail() sends an email with an attachment.
def enviaemail(destinatario, adjunto):
    remitente = "electronic_scale@email.com.uy"
    msg = email.MIMEMultipart()
    msg['From'] = remitente
    msg['To'] = destinatario
    msg['Subject'] = "Ultimo informe de la balanza."
    adjunto = open('C:\\Balanza\\Reportes\\ultimoreporte.pdf', 'rb')
    attach = email.MIMENonMultipart('application', 'pdf')
    payload = base64.b64encode(adjunto.read()).decode('ascii')
    attach.set_payload(payload)
    attach['Content-Transfer-Encoding'] = 'base64'
    adjunto.close()
    attach.add_header('Content-Disposition', 'attachment', filename = 'ultimoreporte.pdf')
    msg.attach(attach)
    server = smtplib.SMTP('smtp.email.com.uy')
    server.login('electronic_scale@email.com.uy', 'thermofischer')
    server.sendmail('electronic_scale@email.com.uy',destinatario, msg.as_string())
    server.quit()


#The main routine, to retrieve the last report and send it by email.
adjunto = descargareporteftp(carpetaftp)
print("Reporte descargado")
enviaemail('myemail@email.com.uy',reporte)
print("Reporte enviado")

【问题讨论】:

  • 你不能使用 os.walk 来查找远程文件。如果你不知道你需要什么文件,你应该使用 ftp list。你也没有传递 obtenerultimoarchivo 函数任何东西。
  • 'obtenerultimoarchivo()' 在 'descargareporteftp()' 内。我将检查 ftp 列表。谢谢。

标签: python file ftp


【解决方案1】:

这是我通过犯错误发现的一种肮脏方式:

如果在 urllib 检索命令中没有指定文件,它将返回目录中的文件列表(如在 ls 命令中)。

因此使用它,代码执行以下操作:

  1. 检索FTP文件夹中的文件列表并将文件保存到本地
  2. 读取文件并找到列表中的最后一个条目
  3. 从 FTP 文件夹中检索最后一个文件

    import urllib
    
    def retrieve(address,output):
       # Run the ftp retrieve command here
       urllib.urlretrieve(address, output)
       # Flush the urllib so that we can download a second file
       urllib.urlcleanup()
    
    def main():
       #let's build the ftp address here:
       usr = "usrname"
       psswrd = "password"
       host = "host.com"
       path = "/foo/bar/"
       list_file = "list"
       address = 'ftp://%s:%s@%s%s' % (usr,psswrd,host,path)
       print "Getting file listing from: " + address
    
       # Retrieve the list
       retrieve(address,list_file)
    
       # read a text file as a list of lines
       # find the last line, change to a file you have
       list_file_reader = open ( 'list',"r" )
       lineList = list_file_reader.readlines()
       last_file = lineList[-1].split(' ')[-1:][0].rstrip()
    
       output = "wanted_file.dat"
       address = 'ftp://%s:%s@%s%s%s' % (usr,psswrd,host,path,last_file)
    
       # Retrieve the file you are actually looking for
       retrieve(address, output)
    
       print address
    
    main()
    

这当然不是最有效的方法,但它适用于我的场景。

参考资料:

Python: download a file over an FTP server

https://www.daniweb.com/programming/software-development/threads/24544/how-do-i-read-the-last-line-of-a-text-file

Downloading second file from ftp fails

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多