s3fs Documentation

repository·main·Indexed 21 days ago

https://github.com/fsspec/s3fs

s3fs provides a Pythonic filesystem interface for Amazon S3, allowing users to interact with S3 buckets as if they were local filesystems. Built on aiobotocore for asynchronous communication, it features the S3FileSystem class for object operations (ls, cp, mv, rm) and the S3File class for file-like I/O. It supports S3-compatible storage (MinIO, Storj), AWS credential auto-discovery, server-side encryption, and bucket version awareness. s3fs is also integrated with pandas, dask, and intake via S3 URLs.

Tokens
2.9K
Snippets
16
Records
21
Agent score
77%

What's inside s3fs

  1. What is s3fs?

    main
    s3fs is a Python library that provides a convenient filesystem interface for Amazon S3. It is built on top of aiobotocore to enable asynchronous S3 operations through a standard filesystem API.
  2. How to use S3FS with Asyncio

    main

    S3FS is built on aiobotocore and supports asynchronous operations. To use it in async code:

    1. Pass asynchronous=True to the S3FileSystem constructor.
    2. Explicitly await s3.set_session() before making calls.
    3. Use the async versions of methods (which typically have a _ prefix, though the documentation notes sync versions exist with the same name).

    Note: For non-async code, the library handles internal async operations (like bulk cp or mv) behind a synchronization layer automatically.

    import asyncio
    from s3fs import S3FileSystem
    
    async def run_program():
        s3 = S3FileSystem(..., asynchronous=True)
        session = await s3.set_session()
        # ... perform work ...
        await session.close()
    
    asyncio.run(run_program())
  3. Quickstart: Locate and read files with S3FileSystem

    main

    Use s3fs.S3FileSystem to interact with S3. For public buckets, initialize with anon=True. You can use methods like ls() to list contents and open() to get a file-like object for reading or writing.

    import s3fs
    s3 = s3fs.S3FileSystem(anon=True)
    s3.ls('my-bucket')
    with s3.open('my-bucket/my-file.txt', 'rb') as f:
        print(f.read())
  4. Configure AWS Credentials

    main

    S3FS can authenticate using several methods:

    • Explicitly: Pass key and secret to the S3FileSystem constructor.
    • Boto Auto-discovery: Rely on environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN), AWS config files (~/.aws/credentials), or EC2 IAM roles.
    • Profiles: Specify a profile via S3FileSystem(profile='PROFILE').
    • Anonymous: Use anon=True for public, read-only access.
  5. Enable Bucket Version Awareness

    main

    If your S3 bucket has object versioning enabled, you can enable version-aware support by setting version_aware=True in the S3FileSystem constructor. This ensures that once a file is opened, the specific version used for reading is maintained, which helps prevent issues during concurrent reads and writes.

    To use this feature:

    1. Initialize the filesystem with version_aware=True.
    2. Use s3.object_version_info('path/to/object') to retrieve version information.
    3. Pass a specific version_id to s3.open() to read a particular version of an object.

    Note: The user must have the necessary IAM permissions to perform GetObjectVersion for this to work.

    import s3fs
    
    # Initialize with version awareness enabled
    s3 = s3fs.S3FileSystem(version_aware=True)
    
    # Open the latest version
    fo = s3.open('versioned_bucket/object')
    
    # Retrieve version info for the object
    versions = s3.object_version_info('versioned_bucket/object')
    
    # Open a specific historical version
    fo_old_version = s3.open('versioned_bucket/object', version_id='SOMEVERSIONID')
  6. Use Server-Side Encryption with s3fs

    main

    You can enable S3 server-side encryption by passing encryption parameters via the s3_additional_kwargs argument when initializing S3FileSystem or when calling methods like s3.open.

    Arguments passed to s3_additional_kwargs are appended to all underlying S3 calls. If you provide both s3_additional_kwargs at the filesystem level and specific **kwargs in a method call (like s3.open), the method-level arguments take precedence as they are applied last.

    For convenience, you can use s3.utils.SSEParams instead of a raw Python dictionary to manage these parameters.

    import s3fs
    
    # Apply encryption to all calls made by this filesystem instance
    s3 = s3fs.S3FileSystem(
        s3_additional_kwargs={'ServerSideEncryption': 'AES256'}
    )
    
    # You can also pass arguments directly to open()
    # fo = s3.open('path/to/file', ServerSideEncryption='AES256')
  7. Set up a development environment for s3fs

    main

    To set up a local development environment for s3fs, install the necessary dependencies using pip from the project root. This includes both the core requirements and the requirements specifically needed for running tests.

    $ pip install -r requirements.txt -r test_requirements.txt
  8. Integrate S3FS with Pandas and Dask

    main

    Libraries like pandas, dask, and intake support S3 URLs (e.g., s3://bucket/path). You can pass configuration directly to s3fs using the storage_options argument.

    import pandas as pd
    # Pass s3fs arguments via storage_options
    df = pd.read_excel("s3://bucket/path/file.xls", storage_options={"anon": True})
  9. Connect to S3-compatible storage (MinIO, Storj, etc.)

    main

    To use S3-compatible services, you must provide an endpoint_url. You can also pass client_kwargs or config_kwargs for provider-specific requirements (like region names or signature versions).

    import s3fs
    
    # MinIO example
    s3 = s3fs.S3FileSystem(key='miniokey...', secret='asecretkey...', endpoint_url='https://...')
    
    # Scaleway example with region
    s3 = s3fs.S3FileSystem(
        key='scaleway-api-key...', 
        secret='scaleway-secretkey...', 
        endpoint_url='https://s3.fr-par.scw.cloud', 
        client_kwargs={'region_name': 'fr-par'}
    )
    
    # OVH example with specific signature version
    s3 = s3fs.S3FileSystem(
        key='ovh-s3-key...', 
        secret='ovh-s3-secretkey...', 
        endpoint_url='https://s3.GRA.cloud.ovh.net', 
        client_kwargs={'region_name': 'GRA'},
        config_kwargs={'signature_version': 's3v4'}
    )