gpt4 book ai didi

python FTP下载具有特定名称的文件

转载 作者:行者123 更新时间:2023-12-04 03:15:29 28 4
gpt4 key购买 nike

我有这个带文件夹的 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)

最佳答案

当您获取文件列表为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 block 中以确保文件在退出 block 时关闭)

关于python FTP下载具有特定名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41447118/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com