具有特定名称

时间:2017-01-03 15:41:42

标签: python

我有这个FTP文件夹,它包含这些文件:

pw201602042000.nc,
 pw201602042010.nc,
 pw201602042020.nc, 
 pw201602042030.nc, 
 pw201602042040.nc,
 pw201602042050.nc,
 pw201602042100.nc,
 pw201602042110.nc, 
 pw201602042120.nc, 
 pw201602042130.nc, 
 pw201602042140.nc,
 pw201602042150.nc, 
 pw201602042200.nc

如何只下载以00结尾的文件?

from ftplib import FTP

server = FTP("ip/serveradress")
server.login("user", "password")

server.retrlines("LIST") 
server.cwd("Folder")

server.sendcmd("TYPE i") # ready for file transfer
server.retrbinary("RETR %s"%("pw201602042300.nc"), open("pw", "wb").write) 

1 个答案:

答案 0 :(得分:0)

当您获取文件列表为list_of_files时,只需使用fnmatch根据通配符匹配文件名:

list_of_files = server.retrlines("LIST")
dest_dir = "."
for name in list_of_files:
    if fnmatch.fnmatch(name,"*00.nc"):
        with open(os.path.join(dest_dir,name), "wb") as f:
            server.retrbinary("RETR {}".format(name), f.write)  

(请注意,您正在同一个"pw"输出文件上编写文件,我更改了该文件,重用原始名称并提供了目标目录变量,并保护open中的with 1}}阻止以确保文件在退出块时关闭)