如何使用Python从ftp文件夹中检索最新文件?

时间:2013-03-26 14:46:50

标签: python file ftp

在我的公司,我们有一个秤,可以在将箱子装入卡车之前检查箱子的重量。如果盒子包含的产品多于或少于可接受的产品,则将盒子拒收并送到另一条传送带上。电子秤记录了操作的性能。文件存储在秤的磁盘中,并使用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")

1 个答案:

答案 0 :(得分:0)

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

如果在urllib retrieve命令中没有指定文件,它将返回目录中的文件列表(如在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()
    
  4. 这当然不是最有效的方式,但它适用于我的场景。

    参考文献:

    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