使用python从不同目录一次下载数据的代码

2024-05-19 03:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手。 我想通过一个代码从这个URL下载数据:“ftp://cddis.nasa.gov/gnss/products/ionex/”。但是,我想要的文件具有以下格式:“代码gxxxx.xxx.Z”。 所有这些文件都在每年(enter image description here)的内部,如下所示:enter image description here。 如何使用python下载这些文件?。你知道吗

到目前为止,我一直在使用wget和以下代码:wgetftp://cddis.nasa.gov/gnss/products/ionex/2008/246/codg0246.07i.Z”,用于每一个文件,但是非常繁琐。你知道吗

谁能帮帮我吗!!。你知道吗

谢谢


Tags: 文件数据代码imageurlheredescriptionnasa
1条回答
网友
1楼 · 发布于 2024-05-19 03:21:16

因为您知道FTP服务器中的结构,所以不必使用ftplib就可以很容易地完成。你知道吗

从服务器(如this question)实际检索目录列表会更干净

(不过,我似乎无法连接到nasa的URL)

我建议阅读here以获得更多关于如何实际执行FTP下载的信息。你知道吗

但像这样的办法也许行得通。(完全披露:我还没有测试过)

import urllib
YEARS_TO_DOWNLOAD = 12
BASE_URL = "ftp://cddis.nasa.gov/gnss/products/ionex/"
FILE_PATTERN = "codg{}.{}.Z"
SAVE_DIR = "/home/your_name/nasa_ftp/"
year = 2006
three_digit_number = 0

for i in range(0, YEARS_TO_DOWNLOAD):
    target = FILE_PATTERN.format(str(year + i), str(three_digit_number.zfill(3))
    try:
        urllib.urlretrieve(BASE_URL + target, SAVE_DIR + target)
    except urllib.error as e:
        print("An error occurred trying to download {}.\nReason: {}".format(target, 
              str(e))
    else:
        print("{} -> {}".format(target, SAVE_DIR + target))

print("Download finished!")

相关问题 更多 >

    热门问题