我有这个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)
答案 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}}阻止以确保文件在退出块时关闭)