【问题标题】:download file using s3fs使用 s3fs 下载文件
【发布时间】:2020-07-21 15:13:50
【问题描述】:

我正在尝试使用 s3fs 库从 s3 存储桶下载 csv 文件。我注意到使用 pandas 编写新的 csv 在某种程度上改变了数据。所以我想直接下载原始状态的文件。

documentation有下载功能但不知道怎么用:

download(self, rpath, lpath[, recursive]):Alias of FilesystemSpec.get.

这是我尝试过的:

import pandas as pd
import datetime
import os
import s3fs
import numpy as np

#Creds for s3
fs = s3fs.S3FileSystem(key=mykey, secret=mysecretkey)
bucket = "s3://mys3bucket/mys3bucket"
files = fs.ls(bucket)[-3:]


#download files:
for file in files:
    with fs.open(file) as f:
        fs.download(f,"test.csv")

AttributeError: 'S3File' object has no attribute 'rstrip'

【问题讨论】:

    标签: python amazon-s3 python-s3fs


    【解决方案1】:
    for file in files:
        fs.download(file,'test.csv')
    

    修改为下载目录下所有文件:

    import pandas as pd
    import datetime
    import os
    import s3fs
    import numpy as np
    
    #Creds for s3
    fs = s3fs.S3FileSystem(key=mykey, secret=mysecretkey)
    bucket = "s3://mys3bucket/mys3bucket"
    
    #files references the entire bucket.
    files = fs.ls(bucket)
    
    for file in files:
        fs.download(file,'test.csv')
    

    【讨论】:

    • 知道如何修改它以下载目录中的所有文件吗?
    • @ZachRieck 我编辑了我的答案以下载所有文件。
    • 不错!这确实需要更多的可见性。我只能在任何地方找到关于如何使用 s3fs 的答案
    • 在我的版本 (0.2.2) 中,fs.download 似乎不存在,但等效的是 fs.get
    【解决方案2】:

    我也将在这里复制我的答案,因为我在更一般的情况下使用了这个:

    # Access Pando
    import s3fs
    #Blocked out url as "enter url here" for security reasons
    fs = s3fs.S3FileSystem(anon=True, client_kwargs={'endpoint_url':"enter url here"})
    
    # List objects in a path and import to array
    # -3 limits output for testing purposes to prevent memory overload
    files = fs.ls('hrrr/sfc/20190101')[-3:]
    
    #Make a staging directory that can hold data as a medium
    os.mkdir("Staging")
    
    #Copy files into that directory (specific directory structure requires splitting strings)
    for file in files:
        item = str(file)
        lst = item.split("/")
        name = lst[3]
        path = "Staging\\" + name
        print(path)
        fs.download(file, path)
    

    请注意,该特定 python 包的文档相当贫乏。我能够找到一些关于 s3fs 在这里接受哪些参数的文档 (https://readthedocs.org/projects/s3fs/downloads/pdf/latest/)。完整的参数列表在最后,尽管它们没有指定参数的含义。以下是 s3fs.download 的一般指南:

    -arg1 (rpath) 是您从中获取文件的源目录。与上述两个答案一样,获得此功能的最佳方法是在您的 s3 存储桶上执行 fs.ls 并将其保存到变量中

    -arg2 (lpath) 是目标目录和文件名。请注意,如果没有有效的输出文件,这将返回 OP 得到的属性错误。我将其定义为路径变量

    -arg3 是可选参数,用于选择递归执行下载

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2013-08-08
      • 2014-12-20
      • 2015-04-08
      相关资源
      最近更新 更多