> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ファイル操作

> Read, write, and manage files within CoreWeave sandbox instances using the CWSandbox client

この例では、`CWSANDBOX_API_KEY` に設定した CoreWeave API アクセストークンを使用します。Forge APIキーによる認証については、[はじめに](/ja/products/sandboxes/get-started)を参照してください。CKS の要件については、[配置モード](/ja/products/sandboxes/placement)を参照してください。

このガイドでは、CWSandbox クライアントを使用して CoreWeave サンドボックス インスタンス内でファイルを読み書きおよび管理する方法を説明します。サンドボックス内外でデータを移動するワークフローを構築する開発者を対象としており、並列アップロードとダウンロード、エラー処理、大規模ファイルのパターンなどが含まれます。

<h2 id="basic-operations">
  基本操作
</h2>

このセクションの例では、最も一般的なファイル操作を扱っています。サンドボックス内のパスへのデータの書き込みと、データの読み戻しです。ファイル操作は `OperationRef` オブジェクトを返します。`.result()` を使用して完了をブロックします。

<h3 id="write-files">
  ファイルを書き込む
</h3>

```python theme={"system"}
from cwsandbox import Sandbox

with Sandbox.run() as sandbox:
    # ファイルにバイト列を書き込む
    sandbox.write_file("/app/data.txt", b"Hello, World!").result()

    # JSONを書き込む
    import json
    config = {"key": "value", "count": 42}
    sandbox.write_file(
        "/app/config.json",
        json.dumps(config).encode()
    ).result()
```

<h3 id="read-files">
  ファイルの読み取り
</h3>

```python theme={"system"}
# ファイルの内容をバイト列として読み込みます
content = sandbox.read_file("/app/data.txt").result()
print(content.decode())  # "こんにちは、世界！"

# JSON を読み込みます
config_bytes = sandbox.read_file("/app/config.json").result()
config = json.loads(config_bytes.decode())
```

<h2 id="parallel-operations">
  並列操作
</h2>

ファイル操作はすぐに戻るため、自然に並列度を高められます。独立したファイルが複数ある場合、アップロードやダウンロードを並列に実行すると、全体の転送時間を短縮できます。

<h3 id="parallel-uploads">
  並列アップロード
</h3>

```python theme={"system"}
from cwsandbox import results

# すべてのアップロードを同時に開始します
write_refs = [
    sandbox.write_file("/app/config.json", config_bytes),
    sandbox.write_file("/app/data.csv", data_bytes),
    sandbox.write_file("/app/model.pkl", model_bytes),
]

# すべてが完了するのを待ちます
results(write_refs)
```

<h3 id="parallel-downloads">
  並列ダウンロード
</h3>

```python theme={"system"}
# すべてのダウンロードを同時に開始
read_refs = [
    sandbox.read_file("/app/output.json"),
    sandbox.read_file("/app/metrics.json"),
    sandbox.read_file("/app/logs.txt"),
]

# すべての結果を取得
output, metrics, logs = results(read_refs)
```

<h2 id="upload-process-download-pattern">
  アップロード・処理・ダウンロードのパターン
</h2>

一般的なワークフローでは、入力ファイルをアップロードし、処理を実行して、結果をダウンロードします。

```python theme={"system"}
from cwsandbox import Sandbox, results

with Sandbox.run() as sandbox:
    # 1. 並列アップロード
    results([
        sandbox.write_file("/app/config.json", config_bytes),
        sandbox.write_file("/app/input.csv", input_bytes),
    ])

    # 2. 逐次処理
    sandbox.exec(["pip", "install", "-r", "requirements.txt"]).result()
    sandbox.exec(["python", "/app/process.py"]).result()

    # 3. 並列ダウンロード
    output, metrics = results([
        sandbox.read_file("/app/output.json"),
        sandbox.read_file("/app/metrics.json"),
    ])
```

<h2 id="error-handling">
  エラー処理
</h2>

ファイル操作は、パスが存在しない場合や書き込み可能でない場合に失敗する可能性があります。これらのケースを処理し、影響を受けるパスを検査するには、`SandboxFileError` をキャッチします。

<h3 id="file-not-found">
  ファイルが見つかりません
</h3>

```python theme={"system"}
from cwsandbox import SandboxFileError

try:
    content = sandbox.read_file("/nonexistent/file.txt").result()
except SandboxFileError as e:
    print(f"File error: {e.filepath}")
```

<h3 id="write-errors">
  書き込みエラー
</h3>

```python theme={"system"}
try:
    sandbox.write_file("/readonly/path.txt", b"data").result()
except SandboxFileError as e:
    print(f"Cannot write to: {e.filepath}")
```

<h2 id="binary-files">
  バイナリファイル
</h2>

ファイル操作では、画像やシリアライズされた Python オブジェクトなど、あらゆるバイナリコンテンツを扱えます。

```python theme={"system"}
# 画像
with open("image.png", "rb") as f:
    sandbox.write_file("/app/image.png", f.read()).result()

# Pickle ファイル（信頼できるソースのデータのみ逆シリアル化してください）
import pickle
model_bytes = pickle.dumps(my_model)
sandbox.write_file("/app/model.pkl", model_bytes).result()

# ダウンロードして逆シリアル化
model_bytes = sandbox.read_file("/app/trained_model.pkl").result()
trained_model = pickle.loads(model_bytes)
```

<Warning>
  信頼できるソースのデータのみを unpickle してください。pickle ファイルを読み込むと、任意のコードが実行される可能性があります。
</Warning>

<h2 id="text-encoding">
  テキストのエンコーディング
</h2>

ファイルはバイト列として転送されるため、非 ASCII 文字の文字化けを防ぐには、テキストを明示的にエンコードおよびデコードする必要があります。

```python theme={"system"}
# テキストを書き込みます
text = "Hello, Unicode! "
sandbox.write_file("/app/text.txt", text.encode("utf-8")).result()

# テキストを読み込みます
content = sandbox.read_file("/app/text.txt").result()
text = content.decode("utf-8")
```

<h2 id="large-file-considerations">
  大きなファイルに関する考慮事項
</h2>

`read_file` および `write_file` API は、小規模から中規模のファイルに適しています。大きなファイルを扱う場合は、次の点を考慮してください。

* ファイルは API を介して転送されるため、帯域幅を考慮してください。
* 大規模なデータセットには、可能な限りストリーミングを使用してください。
* API を介してデータを転送せず、オブジェクトストレージに直接アクセスしてください。

`object_storage_access` パラメーターは、一時的な CoreWeave AI Object Storage の認証情報を作成し、サンドボックスのコンテナーに提供します。これにより、ワークロードはバケットを直接読み書きできるため、大きなオブジェクトが `read_file` や `write_file` を経由することはありません。事前に、組織でサンドボックスのコントロールプレーンに Workload Identity Federation の設定を登録しておく必要があります。詳しくは、[オブジェクトストレージへのアクセス](/ja/products/sandboxes/operations/object-storage-access)を参照してください。

次の例では、CoreWeave 認証を使用して 1 つのバケットへの読み書きアクセス権を持つサンドボックスを起動し、認証情報が注入されたことを確認します。`CWSANDBOX_API_KEY` に設定済みの組織の CoreWeave API アクセストークンを設定し、`[BUCKET-NAME]` をご使用のバケット名に置き換えてください。

```python theme={"system"}
from cwsandbox import AuthStrategy, ObjectStorageAccess, ObjectStoragePermission, Sandbox

with Sandbox.run(
    auth=AuthStrategy.COREWEAVE_API_KEY,
    container_image="python:3.11",
    object_storage_access=ObjectStorageAccess(
        buckets=["[BUCKET-NAME]"],
        permission=ObjectStoragePermission.READ_WRITE,
    ),
) as sandbox:
    result = sandbox.exec(["printenv", "AWS_ENDPOINT_URL_S3"]).result()
    print(result.stdout)
```

サンドボックスには、AWS SDK がコンテナー認証情報の取得時に読み取る環境変数が設定されているため、サンドボックス内の S3互換クライアントは明示的にキーを指定しなくても動作します。これらの変数と Boto3 の例については、[サンドボックス内で認証情報を使用する](/ja/products/sandboxes/operations/object-storage-access#step-5-use-the-credentials-inside-the-sandbox)を参照してください。

認証情報の適用範囲を特定のキー接頭辞に限定するには、`object_prefix` を使用します。データの読み取りのみを行うワークロードには、`ObjectStoragePermission.READ` を使用します。

サンドボックス内でのみ使用する大容量の一時データには、代わりにボリュームをアタッチしてください。詳しくは [Volumes](/ja/products/sandboxes/volumes) を参照してください。
