') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); arrow/docs/source/python/filesystems.rst at main · apache/arrow · GitHub
Skip to content

Latest commit

History

History
462 lines (322 loc) · 17.6 KB

File metadata and controls

462 lines (322 loc) · 17.6 KB
.. currentmodule:: pyarrow.fs

Filesystem Interface

PyArrow comes with an abstract filesystem interface, as well as concrete implementations for various storage types.

The filesystem interface provides input and output streams as well as directory operations. A simplified view of the underlying data storage is exposed. Data paths are represented as abstract paths, which are /-separated, even on Windows, and shouldn't include special path components such as . and ... Symbolic links, if supported by the underlying storage, are automatically dereferenced. Only basic :class:`metadata <FileInfo>` about file entries, such as the file size and modification time, is made available.

The core interface is represented by the base class :class:`FileSystem`.

Pyarrow implements natively the following filesystem subclasses:

It is also possible to use your own fsspec-compliant filesystem with pyarrow functionalities as described in the section :ref:`filesystem-fsspec`.

Usage

Instantiating a filesystem

A FileSystem object can be created with one of the constructors (and check the respective constructor for its options):

>>>frompyarrowimportfs>>>importpyarrowaspa>>>local=fs.LocalFileSystem()

or alternatively inferred from a URI:

>>>s3, path=fs.FileSystem.from_uri("s3://my-bucket") # doctest: +SKIP>>>s3# doctest: +SKIP<pyarrow._s3fs.S3FileSystemat ...>>>>path# doctest: +SKIP'my-bucket'

Reading and writing files

Several of the IO-related functions in PyArrow accept either a URI (and infer the filesystem) or an explicit filesystem argument to specify the filesystem to read or write from. For example, the :meth:`pyarrow.parquet.read_table` function can be used in the following ways:

>>>importpyarrow.parquetaspq>>># using a URI -> filesystem is inferred>>>pq.read_table("s3://my-bucket/data.parquet") # doctest: +SKIP>>># using a path and filesystem>>>s3=fs.S3FileSystem(..) # doctest: +SKIP>>>pq.read_table("my-bucket/data.parquet", filesystem=s3) # doctest: +SKIP

The filesystem interface further allows to open files for reading (input) or writing (output) directly, which can be combined with functions that work with file-like objects. For example:

>>>table=pa.table({'col1': [1, 2, 3]})
>>>local=fs.LocalFileSystem()
>>>withlocal.open_output_stream("test.arrow") asfile:
... withpa.RecordBatchFileWriter(file, table.schema) aswriter:
... writer.write_table(table)

Listing files

Inspecting the directories and files on a filesystem can be done with the :meth:`FileSystem.get_file_info` method. To list the contents of a directory, use the :class:`FileSelector` object to specify the selection:

>>>local.get_file_info(fs.FileSelector("dataset/", recursive=True)) # doctest: +SKIP
[<FileInfofor'dataset/part=B': type=FileType.Directory>,
<FileInfofor'dataset/part=B/data0.parquet': type=FileType.File, size=1564>,
<FileInfofor'dataset/part=A': type=FileType.Directory>,
<FileInfofor'dataset/part=A/data0.parquet': type=FileType.File, size=1564>]

This returns a list of :class:`FileInfo` objects, containing information about the type (file or directory), the size, the date last modified, etc.

You can also get this information for a single explicit path (or list of paths):

>>>local.get_file_info('test.arrow')
<FileInfofor'test.arrow': type=FileType.File, size=498>>>>local.get_file_info('non_existent')
<FileInfofor'non_existent': type=FileType.NotFound>

Local FS

The :class:`LocalFileSystem` allows you to access files on the local machine.

Example how to write to disk and read it back:

>>>local=fs.LocalFileSystem()
>>>withlocal.open_output_stream('pyarrowtest.dat') asstream:
... stream.write(b'data')
4>>>withlocal.open_input_stream('pyarrowtest.dat') asstream:
... print(stream.readall())
b'data'

S3

PyArrow implements natively a S3 filesystem for S3 compatible storage.

The :class:`S3FileSystem` constructor has several options to configure the S3 connection (e.g. credentials, the region, an endpoint override, etc). In addition, the constructor will also inspect configured S3 credentials as supported by AWS (such as the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, AWS configuration files, and EC2 Instance Metadata Service for EC2 nodes).

Example how you can read contents from a S3 bucket:

>>>s3=fs.S3FileSystem(region='eu-west-3') # doctest: +SKIP>>># List all contents in a bucket, recursively>>>s3.get_file_info(fs.FileSelector('my-test-bucket', recursive=True)) # doctest: +SKIP
[<FileInfofor'my-test-bucket/File1': type=FileType.File, size=10>,
<FileInfofor'my-test-bucket/File5': type=FileType.File, size=10>,
<FileInfofor'my-test-bucket/Dir1': type=FileType.Directory>,
<FileInfofor'my-test-bucket/Dir2': type=FileType.Directory>,
<FileInfofor'my-test-bucket/EmptyDir': type=FileType.Directory>,
<FileInfofor'my-test-bucket/Dir1/File2': type=FileType.File, size=11>,
<FileInfofor'my-test-bucket/Dir1/Subdir': type=FileType.Directory>,
<FileInfofor'my-test-bucket/Dir2/Subdir': type=FileType.Directory>,
<FileInfofor'my-test-bucket/Dir2/Subdir/File3': type=FileType.File, size=10>]
>>># Open a file for reading and download its contents>>>f=s3.open_input_stream('my-test-bucket/Dir1/File2') # doctest: +SKIP>>>f.readall() # doctest: +SKIPb'some data'

Note that it is important to configure :class:`S3FileSystem` with the correct region for the bucket being used. If region is not set, the AWS SDK will choose a value, defaulting to 'us-east-1' if the SDK version is <1.8. Otherwise it will try to use a variety of heuristics (environment variables, configuration profile, EC2 metadata server) to resolve the region.

It is also possible to resolve the region from the bucket name for :class:`S3FileSystem` by using :func:`pyarrow.fs.resolve_s3_region` or :func:`pyarrow.fs.S3FileSystem.from_uri`.

Here are a couple examples in code:

>>>s3=fs.S3FileSystem(region=fs.resolve_s3_region('my-test-bucket')) # doctest: +SKIP>>># Or via URI:>>>s3, path=fs.S3FileSystem.from_uri('s3://[access_key:secret_key@]bucket/path]') # doctest: +SKIP
.. seealso::
See the `AWS docs <https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html>`__
for the different ways to configure the AWS credentials.
:func:`pyarrow.fs.resolve_s3_region` for resolving region from a bucket name.

Troubleshooting

When using :class:`S3FileSystem`, output is only produced for fatal errors or when printing return values. For troubleshooting, the log level can be set using the environment variable ARROW_S3_LOG_LEVEL. The log level must be set prior to running any code that interacts with S3. Possible values include FATAL (the default), ERROR, WARN, INFO, DEBUG (recommended), TRACE, and OFF.

Google Cloud Storage File System

PyArrow implements natively a Google Cloud Storage (GCS) backed file system for GCS storage.

If not running on Google Cloud Platform (GCP), this generally requires the environment variable GOOGLE_APPLICATION_CREDENTIALS to point to a JSON file containing credentials. Alternatively, use the gcloud CLI to generate a credentials file in the default location:

gcloud auth application-default login

To connect to a public bucket without using any credentials, you must pass anonymous=True to :class:`GcsFileSystem`. Otherwise, the filesystem will report Couldn't resolve host name since there are different host names for authenticated and public access.

Example showing how you can read contents from a GCS bucket:

>>>fromdatetimeimporttimedelta>>>gcs=fs.GcsFileSystem(anonymous=True, retry_time_limit=timedelta(seconds=15)) # doctest: +SKIP>>># List all contents in a bucket, recursively>>>uri="gcp-public-data-landsat/LC08/01/001/003/"# doctest: +SKIP>>>file_list=gcs.get_file_info(fs.FileSelector(uri, recursive=True)) # doctest: +SKIP>>># Open a file for reading and download its contents>>>f=gcs.open_input_stream(file_list[0].path) # doctest: +SKIP>>>f.read(64) # doctest: +SKIPb'GROUP = FILE_HEADER\n LANDSAT_SCENE_ID = "LC80010032013082LGN03"\n S'
.. seealso::
The :class:`GcsFileSystem` constructor by default uses the
process described in `GCS docs <https://google.aip.dev/auth/4110>`__
to resolve credentials.

Hadoop Distributed File System (HDFS)

PyArrow comes with bindings to the Hadoop File System (based on C++ bindings using libhdfs, a JNI-based interface to the Java Hadoop client). You connect using the :class:`HadoopFileSystem` constructor:

>>>hdfs=fs.HadoopFileSystem(host, port, user=user, kerb_ticket=ticket_cache_path) # doctest: +SKIP

The libhdfs library is loaded at runtime (rather than at link / library load time, since the library may not be in your LD_LIBRARY_PATH), and relies on some environment variables.

  • HADOOP_HOME: the root of your installed Hadoop distribution. Often has lib/native/libhdfs.so.

  • JAVA_HOME: the location of your Java SDK installation.

  • ARROW_LIBHDFS_DIR (optional): explicit location of libhdfs.so if it is installed somewhere other than $HADOOP_HOME/lib/native.

  • CLASSPATH: must contain the Hadoop jars. You can set these using:

    >>> export CLASSPATH=`$HADOOP_HOME/bin/hadoop classpath --glob`# doctest: +SKIP
    >>> # or on Windows
    >>> %HADOOP_HOME%/bin/hadoop classpath --glob > %CLASSPATH% # doctest: +SKIP

    In contrast to the legacy HDFS filesystem with pa.hdfs.connect, setting CLASSPATH is not optional (pyarrow will not attempt to infer it).

Azure Storage File System

PyArrow implements natively an Azure filesystem for Azure Blob Storage with or without heirarchical namespace enabled.

The :class:`AzureFileSystem` constructor has several options to configure the Azure Blob Storage connection (e.g. account name, account key, SAS token, etc.).

If neither account_key or sas_token is specified a DefaultAzureCredential is used for authentication. This means it will try several types of authentication and go with the first one that works. If any authentication parameters are provided when initialising the FileSystem, they will be used instead of the default credential.

Example showing how you can read contents from an Azure Blob Storage account:

>>>azure_fs=fs.AzureFileSystem(account_name='myaccount') # doctest: +SKIP>>># List all contents in a container, recursively>>>azure_fs.get_file_info(fs.FileSelector('my-container', recursive=True)) # doctest: +SKIP
[<FileInfofor'my-container/File1': type=FileType.File, size=10>,
<FileInfofor'my-container/File2': type=FileType.File, size=20>,
<FileInfofor'my-container/Dir1': type=FileType.Directory>,
<FileInfofor'my-container/Dir1/File3': type=FileType.File, size=30>]
>>># Open a file for reading and download its contents>>>f=azure_fs.open_input_stream('my-container/File1') # doctest: +SKIP>>>f.readall() # doctest: +SKIPb'some data'

For more details on the parameters and usage, refer to the :class:`AzureFileSystem` class documentation.

.. seealso::
See the `Azure SDK for C++ documentation <https://github.com/Azure/azure-sdk-for-cpp>`__
for more information on authentication and configuration options.

Using fsspec-compatible filesystems with Arrow

The filesystems mentioned above are natively supported by Arrow C++ / PyArrow. The Python ecosystem, however, also has several filesystem packages. Those packages following the fsspec interface can be used in PyArrow as well.

Functions accepting a filesystem object will also accept an fsspec subclass. For example:

>>># creating an fsspec-based filesystem object for Google Cloud Storage>>>importgcsfs# doctest: +SKIP>>>fs_gcs=gcsfs.GCSFileSystem(project='my-google-project') # doctest: +SKIP>>># using this to read a partitioned dataset>>>importpyarrow.datasetasds# doctest: +SKIP>>>ds.dataset("data/", filesystem=fs_gcs) # doctest: +SKIP

Similarly for Azure Blob Storage:

>>>importadlfs# doctest: +SKIP>>># ... load your credentials and configure the filesystem>>>fs_azure=adlfs.AzureBlobFileSystem(account_name=account_name, account_key=account_key) # doctest: +SKIP>>>ds.dataset("mycontainer/data/", filesystem=fs_azure) # doctest: +SKIP

Under the hood, the fsspec filesystem object is wrapped into a python-based PyArrow filesystem (:class:`PyFileSystem`) using :class:`FSSpecHandler`. You can also manually do this to get an object with the PyArrow FileSystem interface:

>>>frompyarrow.fsimportPyFileSystem, FSSpecHandler# doctest: +SKIP>>>pa_fs=PyFileSystem(FSSpecHandler(fs_azure)) # doctest: +SKIP

Then all the functionalities of :class:`FileSystem` are accessible:

>>># write data>>>withpa_fs.open_output_stream('mycontainer/pyarrowtest.dat') asstream: # doctest: +SKIP
... stream.write(b'data')
>>># read data>>>withpa_fs.open_input_stream('mycontainer/pyarrowtest.dat') asstream: # doctest: +SKIP
... print(stream.readall())
b'data'>>># read a partitioned dataset>>>ds.dataset("data/", filesystem=pa_fs) # doctest: +SKIP

Using fsspec-compatible filesystem URIs

PyArrow can automatically instantiate fsspec filesystems by prefixing the URI scheme with fsspec+. This allows you to use the fsspec-compatible filesystems directly with PyArrow's IO functions without needing to manually create a filesystem object. Example writing and reading a Parquet file using an in-memory filesystem provided by fsspec:

>>>table=pa.table({'a': [1, 2, 3]})
>>>pq.write_table(table, "fsspec+memory://path/to/my_table.parquet") # doctest: +SKIP>>>pq.read_table("fsspec+memory://path/to/my_table.parquet") # doctest: +SKIP

Example reading parquet file from GitHub directly:

>>>pq.read_table("fsspec+github://apache:arrow-testing@/data/parquet/alltypes-java.parquet") # doctest: +SKIP

Hugging Face URIs are explicitly allowed as a shortcut without needing to prefix with fsspec+. This is useful for reading datasets hosted on Hugging Face:

>>>pq.read_table("hf://datasets/stanfordnlp/imdb/plain_text/train-00000-of-00001.parquet") # doctest: +SKIP

Using Arrow filesystems with fsspec

The Arrow FileSystem interface has a limited, developer-oriented API surface. This is sufficient for basic interactions and for using this with Arrow's IO functionality. On the other hand, the fsspec interface provides a very large API with many helper methods. If you want to use those, or if you need to interact with a package that expects fsspec-compatible filesystem objects, you can wrap an Arrow FileSystem object with fsspec.

Starting with fsspec version 2021.09, the ArrowFSWrapper can be used for this:

>>>local=fs.LocalFileSystem()
>>>fromfsspec.implementations.arrowimportArrowFSWrapper# doctest: +SKIP>>>local_fsspec=ArrowFSWrapper(local) # doctest: +SKIP

The resulting object now has an fsspec-compatible interface, while being backed by the Arrow FileSystem under the hood. Example usage to create a directory and file, and list the content:

>>>local_fsspec.mkdir("./test") # doctest: +SKIP>>>local_fsspec.touch("./test/file.txt") # doctest: +SKIP>>>local_fsspec.ls("./test/") # doctest: +SKIP
['./test/file.txt']

For more information, see the fsspec documentation.