【问题标题】:Python send a file via ftp with the random file namePython 通过 ftp 使用随机文件名发送文件
【发布时间】:2016-11-07 11:18:42
【问题描述】:

您好,我创建了一个脚本,用于在 ftp 服务器上发送一个名为 office-data.txt 的文件,但我希望这个脚本在将文件发送到 FTP 服务器时,必须随机更改其名称,仅远程,例如 office-data-12478.txt 或 office-data-22478.txt 并且每次脚本启动时随机生成的名称不能相同,如何修改此脚本以在发送时更改文件名到 FTP 服务器?

import ftplib

sftp = ftplib.FTP('ftp.example.com','userexample','passexample') # Connect
fp = open('office-data.txt','rb') # file to send
sftp.storbinary('STOR office-data.txt', fp) # Send the file

fp.close() # Close file and FTP
sftp.quit()

【问题讨论】:

    标签: python file ftp


    【解决方案1】:

    您可以使用 UUID 生成随机名称。

    import uuid
    
    sftp.storlines(filename + str(uuid.uuid4()), open(filename, 'r'))
    

    【讨论】:

      【解决方案2】:

      您可以使用uuid 或当前时间戳以毫秒为单位。

      import ftplib
      import uuid
      
      unique_id = str(uuid.uuid4())
      sftp = ftplib.FTP('ftp.exampple','userexample','passexample') # Connect
      fp = open('office-data.txt','rb') # file to send
      sftp.storbinary('STOR office-data-{0}.txt'.format(unique_id), fp) # Send the file
      
      fp.close() # Close file and FTP
      sftp.quit()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        • 2012-10-04
        相关资源
        最近更新 更多