File
File is a special DataModel,
which is automatically generated when a DataChain is created from files,
such as in dc.read_storage:
Output:
File classes include various metadata fields describing the underlying file,
along with methods to read and manipulate file contents.
File
Bases: DataModel
DataModel for reading binary files.
Attributes:
-
source(str) –The source of the file (e.g., 's3://bucket-name/').
-
path(str) –The path to the file (e.g., 'path/to/file.txt').
-
size(int) –The size of the file in bytes. Defaults to 0.
-
version(str) –The version of the file. Defaults to an empty string.
-
etag(str) –The ETag of the file. Defaults to an empty string.
-
is_latest(bool) –Whether the file is the latest version. Defaults to
True. -
last_modified(datetime) –The last modified timestamp of the file. Defaults to Unix epoch (
1970-01-01T00:00:00). -
location(dict | list[dict]) –The location of the file. Defaults to
None.
Source code in datachain/lib/file.py
name
property
The file name extracted from the path.
Example
parent
property
The parent directory of the file, extracted from the path.
Example
as_audio_file
Convert the file to a AudioFile object.
Source code in datachain/lib/file.py
as_image_file
Convert the file to a ImageFile object.
Source code in datachain/lib/file.py
as_text_file
Convert the file to a TextFile object.
Source code in datachain/lib/file.py
as_video_file
Convert the file to a VideoFile object.
Source code in datachain/lib/file.py
at
classmethod
Construct a File from a full URI in one call.
Parameters:
-
uri(str | PathLike[str]) –Full URI or path to the file (e.g.
s3://bucket/path/to/file.pngor/local/path). -
session(Session | None, default:None) –Optional session instance. If None, the current session is used.
Returns:
-
File(Self) –A new File object pointing to the given URI.
Example
Source code in datachain/lib/file.py
ensure_cached
Download the file to the local cache.
get_local_path can be used to return the path to the cached copy on disk.
This is useful when you need to pass the file to code that expects a local
filesystem path (e.g. ffmpeg, opencv, pandas, etc).
Example
Source code in datachain/lib/file.py
export
Copy or link this file into an output directory.
Parameters:
-
output(str | PathLike[str]) –Destination directory. Accepts a local OS path, a cloud prefix fsspec URI (
s3://…,gs://…,az://…). -
placement(ExportPlacement, default:'fullpath') –How to build the path under output:
"fullpath"(default) —output/bucket/dir/file.txt"filepath"—output/dir/file.txt"filename"—output/file.txt"etag"—output/<etag>.txt
-
use_cache(bool, default:True) –If True, download to local cache first. Also required for symlinking remote files.
-
link_type(Literal['copy', 'symlink'], default:'copy') –"copy"(default) or"symlink". Symlink falls back to copy for virtual files and for remote files when use_cache is False. -
client_config(dict | None, default:None) –Extra kwargs forwarded to the storage client.
-
content_type(str | None, default:None) –Content-Typeto set on the exported object. -
content_disposition(str | None, default:None) –Content-Dispositionto set on the object. -
cache_control(str | None, default:None) –Cache-Controlto set on the object. -
content_encoding(str | None, default:None) –Content-Encodingto set on the object. -
metadata(dict[str, str] | None, default:None) –Custom key/value metadata to attach to the object.
-
write_options(dict[str, Any] | None, default:None) –Raw, backend-native write kwargs merged after the normalized fields above. Object metadata is applied only to copied (not symlinked) files and is ignored on the local filesystem.
Example
Source code in datachain/lib/file.py
get_fs_path
Combine source and path into the full location string.
For cloud backends the result is a full URI-like (s3://…, gs://…).
For local files the result is a bare OS path (no file://
prefix).
Examples:
Raises:
-
FileError–If
pathis empty, ends with/, or contains./..segments. For local files, also rejects absolute paths, drive letters, and empty segments.
Source code in datachain/lib/file.py
get_local_path
Return path to a file in a local cache.
Returns None if file is not cached. Raises an exception if cache is not setup.
Source code in datachain/lib/file.py
open
Open the file and return a file-like object.
Supports both read ("rb", "r") and write modes (e.g. "wb", "w", "ab"). When opened in a write mode, metadata is refreshed after closing.
Reads always consult the cache (hit → local, miss → remote stream);
_caching_enabled only governs whether a miss is also persisted.
In write modes, content_type, content_disposition,
cache_control, content_encoding, metadata and the raw
write_options escape hatch set object metadata on the written
object (mapped per backend, ignored on the local filesystem).
block_size sets the read-ahead block for uncached remote reads, and
the upload part size for writes. HTTP(S) reads ignore it.
Source code in datachain/lib/file.py
read
Returns file contents.
Source code in datachain/lib/file.py
read_bytes
Returns file contents as bytes.
Source code in datachain/lib/file.py
read_text
Return file contents decoded as text.
**open_kwargs : Any
Extra keyword arguments forwarded to open(mode="r", ...)
(e.g. encoding="utf-8", errors="ignore")
Source code in datachain/lib/file.py
rebase
Rebase the file's URI from one base directory to another.
Parameters:
-
old_base(str) –Base directory to remove from the file's URI
-
new_base(str) –New base directory to prepend
-
suffix(str, default:'') –Optional suffix to add before file extension
-
extension(str, default:'') –Optional new file extension (without dot)
Returns:
-
str(str) –Rebased URI with new base directory
Raises:
-
ValueError–If old_base is not found in the file's URI
Examples:
Source code in datachain/lib/file.py
resolve
Resolve a File object by checking its existence and updating its metadata.
Returns:
-
File(Self) –The resolved File object with updated metadata.
Source code in datachain/lib/file.py
save
Write file contents to destination.
Parameters:
-
destination(str) –Target path or URI. Accepts a local OS path, a cloud URI (
s3://…,gs://…,az://…), or an unencodedfile://URI as produced by :func:~datachain.fs.utils.path_to_fsspec_uri. Do not passPath.as_uri()output — that produces RFC percent-encoded URIs (e.g.file:///my%20dir) which fsspec does not decode, causingFileNotFoundErrorfor paths containing spaces,#, or%. -
client_config(dict | None, default:None) –Optional extra kwargs forwarded to the storage client (e.g. credentials, endpoint URL).
-
content_type(str | None, default:None) –Content-Typeto set on the written object. -
content_disposition(str | None, default:None) –Content-Dispositionto set on the object. -
cache_control(str | None, default:None) –Cache-Controlto set on the object. -
content_encoding(str | None, default:None) –Content-Encodingto set on the object. -
metadata(dict[str, str] | None, default:None) –Custom key/value metadata to attach to the object.
-
write_options(dict[str, Any] | None, default:None) –Raw, backend-native write kwargs merged after the normalized fields; forwarded on S3 only (e.g.
{"ACL": "public-read"}) and rejected on GCS/Azure.
The normalized metadata fields are mapped to each backend's native parameters and ignored by the local filesystem.
Returns:
-
File–A
Filerepresenting the newly written destination, with -
File–versionpopulated on versioned backends.
Example
Source code in datachain/lib/file.py
upload
classmethod
Upload bytes to a storage path and return a File pointing to it.
Parameters:
-
data(bytes) –The raw bytes to upload.
-
path(str | PathLike[str]) –Destination path (local or remote, e.g.
s3://bucket/file.txt). -
catalog(Catalog | None, default:None) –Optional catalog instance. If None, the current session catalog is used.
-
content_type(str | None, default:None) –Content-Typeto set on the object. -
content_disposition(str | None, default:None) –Content-Dispositionto set on the object. -
cache_control(str | None, default:None) –Cache-Controlto set on the object. -
content_encoding(str | None, default:None) –Content-Encodingto set on the object. -
metadata(dict[str, str] | None, default:None) –Custom key/value metadata to attach to the object.
-
write_options(dict[str, Any] | None, default:None) –Raw, backend-native write kwargs merged after the normalized fields; forwarded on S3 only (e.g.
{"ACL": "public-read"}) and rejected on GCS/Azure.
The normalized metadata fields are mapped to each backend's native parameters and ignored by the local filesystem.
Returns:
-
File(Self) –A new File object with metadata populated from the upload.
Example
Note
To write data as a stream, use File.at with open instead:
Source code in datachain/lib/file.py
TarVFile
Bases: VFile
Virtual file model for files extracted from tar archives.
open
classmethod
Stream file from tar archive based on location in archive.
Reads always consult the cache (hit → local, miss → remote stream);
_caching_enabled only governs whether a miss is also persisted.