首页 > 解决方案 > python删除超过x天的文件夹

问题描述

我想在 ftp 服务器上创建一个早于 x 天的 python 脚本。

我已经完成了 ftp 部分,但是要删除我没有解决方案的文件夹,有人可以帮助您遇到下面的问题,您可以找到我目前拥有的代码。

ftp = FTP('ftp.my.webhosting.be')
ftp.login('user@localhost.be', 'xyz')
path = 'Export/XML/Stocks/_PROCESSED'

print('Changing Directory to : ' + path)
ftp.cwd(path)
# List Contents
ftp.dir()

# Get the currecnt time
now = time.time()

# Delete folders older than 5 days

print('Closing FTP connection')
ftp.close()

标签: pythondirectoryftp

解决方案


from dateutil import parser

ftp = FTP('ftp.my.webhosting.be')
ftp.login('user@localhost.be', 'xyz')
path = 'Export/XML/Stocks/_PROCESSED'

print('Changing Directory to : ' + path)
ftp.cwd(path)
# List Contents

files = ftp.dir()

# Get the currecnt time
now = time.time()

# Delete folders older than 5 days

for file in files:
    timestamp = ftp.voidcmd(f"MDTM {file}")[4:].strip() # Not sure if correct, but as an indication
    fileTime = parser.parse(timestamp) # you have to double check these, but this would be my approach
    timediff = fileTime - now # Again not sure if this would work, but good approach

    # if (timediff > 5 days):
    #   deletefile()    

print('Closing FTP connection')
ftp.close()

这可能是一种方法,我不知道这个特定代码是否有效,因为我没有访问 FTP 服务器的权限。但这应该是一个好方法。


推荐阅读