Repository: conda/conda (language: python)

Issue:
conda env export --file=<> --json throws TypeError
### Checklist

- [x] I added a descriptive title
- [x] I searched open reports and couldn't find a duplicate

### What happened?

Attempting to use `conda env export --file=<>` to write a YAML file, whilst at the same time asking for output (progress) to be reported as JSON with `--json` results in a `TypeError`:

To reproduce

```shell
conda create -n test go
conda env export --name test --json --file test.yml
```

Result:

```json
{
  "command": "/home/duncan/opt/conda/bin/conda env export --name test --json --file test.yml",
  "conda_info": {
    "GID": 1000,
    "UID": 1000,
    "active_prefix": "/home/duncan/opt/conda/envs/test",
    "active_prefix_name": "test",
    "av_data_dir": "/home/duncan/opt/conda/etc/conda",
    "av_metadata_url_base": null,
    "channels": [
      "https://conda.anaconda.org/conda-forge/linux-64",
      "https://conda.anaconda.org/conda-forge/noarch",
      "https://conda.anaconda.org/igwn/linux-64",
      "https://conda.anaconda.org/igwn/noarch"
    ],
    "conda_build_version": "24.7.1",
    "conda_env_version": "24.9.1",
    "conda_location": "/home/duncan/opt/conda/lib/python3.12/site-packages/conda",
    "conda_prefix": "/home/duncan/opt/conda",
    "conda_shlvl": 2,
    "conda_version": "24.9.1",
    "config_files": [
      "/home/duncan/opt/conda/.condarc",
      "/home/duncan/.condarc"
    ],
    "default_prefix": "/home/duncan/opt/conda/envs/test",
    "env_vars": {
      "CIO_TEST": "<not set>",
      "CONDA_ALLOW_SOFTLINKS": "false",
      "CONDA_BACKUP_ADDR2LINE": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-addr2line",
      "CONDA_BACKUP_AR": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ar",
      "CONDA_BACKUP_AS": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-as",
      "CONDA_BACKUP_BUILD": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CC": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cc",
      "CONDA_BACKUP_CC_FOR_BUILD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cc",
      "CONDA_BACKUP_CFLAGS": "-march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CMAKE_PREFIX_PATH": "/home/duncan/opt/conda/envs/py312:/home/duncan/opt/conda/envs/py312/x86_64-conda-linux-gnu/sysroot/usr",
      "CONDA_BACKUP_CONDA_BUILD_SYSROOT": "/home/duncan/opt/conda/envs/py312/x86_64-conda-linux-gnu/sysroot",
      "CONDA_BACKUP_CONDA_TOOLCHAIN_BUILD": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CONDA_TOOLCHAIN_HOST": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CPP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cpp",
      "CONDA_BACKUP_CPPFLAGS": "-DNDEBUG -D_FORTIFY_SOURCE=2 -O2 -isystem /home/duncan/opt/conda/envs/py312/include -DNDEBUG -D_FORTIFY_SOURCE=2 -O2 -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CXX": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++",
      "CONDA_BACKUP_CXXFILT": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++filt",
      "CONDA_BACKUP_CXXFLAGS": "-fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CXX_FOR_BUILD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++",
      "CONDA_BACKUP_DEBUG_CFLAGS": "-march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DEBUG_CPPFLAGS": "-D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem /home/duncan/opt/conda/envs/py312/include -D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DEBUG_CXXFLAGS": "-fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DWP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-dwp",
      "CONDA_BACKUP_ELFEDIT": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-elfedit",
      "CONDA_BACKUP_GCC": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc",
      "CONDA_BACKUP_GCC_AR": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-ar",
      "CONDA_BACKUP_GCC_NM": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-nm",
      "CONDA_BACKUP_GCC_RANLIB": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-ranlib",
      "CONDA_BACKUP_GOROOT": "",
      "CONDA_BACKUP_GPROF": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gprof",
      "CONDA_BACKUP_GXX": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-g++",
      "CONDA_BACKUP_HOST": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_LD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ld",
      "CONDA_BACKUP_LDFLAGS": "-Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,--allow-shlib-undefined -Wl,-rpath,/home/duncan/opt/conda/envs/py312/lib -Wl,-rpath-link,/home/duncan/opt/conda/envs/py312/lib -L/home/duncan/opt/conda/envs/py312/lib -Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,--allow-shlib-undefined -Wl,-rpath,/home/duncan/opt/conda/envs/py312/lib -Wl,-rpath-link,/home/duncan/opt/conda/envs/py312/lib -L/home/duncan/opt/conda/envs/py312/lib",
      "CONDA_BACKUP_LD_GOLD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ld.gold",
      "CONDA_BACKUP_MESON_ARGS": "--buildtype release",
      "CONDA_BACKUP_NM": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-nm",
      "CONDA_BACKUP_OBJCOPY": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-objcopy",
      "CONDA_BACKUP_OBJDUMP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-objdump",
      "CONDA_BACKUP_RANLIB": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ranlib",
      "CONDA_BACKUP_READELF": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-readelf",
      "CONDA_BACKUP_SIZE": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-size",
      "CONDA_BACKUP_STRINGS": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-strings",
      "CONDA_BACKUP_STRIP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-strip",
      "CONDA_BACKUP__CONDA_PYTHON_SYSCONFIGDATA_NAME": "_sysconfigdata_x86_64_conda_cos6_linux_gnu",
      "CONDA_BACKUP_build_alias": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_host_alias": "x86_64-conda-linux-gnu",
      "CONDA_DEFAULT_ENV": "test",
      "CONDA_EXE": "/home/duncan/opt/conda/bin/conda",
      "CONDA_PATH": "/home/duncan/opt/conda",
      "CONDA_PREFIX": "/home/duncan/opt/conda/envs/test",
      "CONDA_PREFIX_1": "/home/duncan/opt/conda/envs/py312",
      "CONDA_PROMPT_MODIFIER": "(test) ",
      "CONDA_PYTHON_EXE": "/home/duncan/opt/conda/bin/python",
      "CONDA_ROOT": "/home/duncan/opt/conda",
      "CONDA_SHLVL": "2",
      "CONDA_SMITHY_LOGLEVEL": "DEBUG",
      "CURL_CA_BUNDLE": "<not set>",
      "LD_PRELOAD": "<not set>",
      "MATLABPATH": "/home/duncan/svn/advLigoRTS/trunk/src/epics/simLink:/home/duncan/svn/advLigoRTS/trunk/src/epics/simLink/lib",
      "PATH": "/home/duncan/opt/conda/envs/test/bin:/home/duncan/bin:/home/duncan/opt/conda/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib:/mnt/c/windows/system32:/mnt/c/windows:/mnt/c/windows/System32/Wbem:/mnt/c/windows/System32/WindowsPowerShell/v1.0:/mnt/c/windows/System32/OpenSSH:/mnt/c/Program Files (x86)/Novell/ZENworks/bin:/mnt/c/Program Files/Git/cmd:/mnt/c/Program Files (x86)/GnuPG/bin:/mnt/c/Program Files (x86)/Windows Kits/10/Windows Performance Toolkit:/mnt/c/ProgramData/chocolatey/bin:/mnt/c/Program Files/PowerShell/7:/mnt/c/Program Files/Docker/Docker/resources/bin:/mnt/c/windows/system32/config/systemprofile/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/spxdmm/AppData/Local/Programs/oh-my-posh/bin:/mnt/c/Users/spxdmm/AppData/Local/Programs/Microsoft VS Code/bin:/mnt/c/Program Files/Lens/resources/cli/bin:/mnt/c/Users/spxdmm/AppData/Local/Programs/Lens/resources/cli/bin:/mnt/c/Program Files/Vim/vim91:/home/duncan/bin",
      "PYTHONWARNINGS": ",default::DeprecationWarning,default::PendingDeprecationWarning,ignore:You passed a bytestring:DeprecationWarning,ignore:The SafeConfigParser:DeprecationWarning,ignore:This method will be removed in future versions.  Use 'parser.read_file()' instead:DeprecationWarning,ignore:elementwise != comparison failed; this will raise an error in the future:DeprecationWarning,ignore:the imp module:DeprecationWarning,ignore:metadata:DeprecationWarning,ignore:Using or importing the ABCs:DeprecationWarning,ignore:'U' mode is deprecated,ignore:examples,ignore:The text.latex.unicode,ignore:distutils Version classes are deprecated:DeprecationWarning:requests_mock,ignore:Deprecated call to `pkg_resources:DeprecationWarning,ignore:pkg_resources is deprecated,ignore:conda.:DeprecationWarning,ignore:conda.:PendingDeprecationWarning,ignore:datetime.datetime:DeprecationWarning:boltons.timeutils,ignore:nodes.Node::sphinxcontrib.programoutput",
      "REQUESTS_CA_BUNDLE": "<not set>",
      "SSL_CERT_FILE": "<not set>"
    },
    "envs": [],
    "envs_dirs": [
      "/home/duncan/opt/conda/envs",
      "/home/duncan/.conda/envs"
    ],
    "netrc_file": null,
    "offline": false,
    "pkgs_dirs": [
      "/home/duncan/opt/conda/pkgs",
      "/home/duncan/.conda/pkgs"
    ],
    "platform": "linux-64",
    "python_version": "3.12.3.final.0",
    "rc_path": "/home/duncan/.condarc",
    "requests_version": "2.32.3",
    "root_prefix": "/home/duncan/opt/conda",
    "root_writable": true,
    "site_dirs": [],
    "solver": {
      "default": true,
      "name": "libmamba",
      "user_agent": "solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9"
    },
    "sys.executable": "/home/duncan/opt/conda/bin/python",
    "sys.prefix": "/home/duncan/opt/conda",
    "sys.version": "3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:38:13) [GCC 12.3.0]",
    "sys_rc_path": "/home/duncan/opt/conda/.condarc",
    "user_agent": "conda/24.9.1 requests/2.32.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2 debian/12.7 glibc/2.36 solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9",
    "user_rc_path": "/home/duncan/.condarc",
    "virtual_pkgs": [
      [
        "__archspec",
        "1",
        "skylake"
      ],
      [
        "__conda",
        "24.9.1",
        "0"
      ],
      [
        "__glibc",
        "2.36",
        "0"
      ],
      [
        "__linux",
        "5.15.153.1",
        "0"
      ],
      [
        "__unix",
        "0",
        "0"
      ]
    ]
  },
  "error": "TypeError(\"a bytes-like object is required, not 'str'\")",
  "exception_name": "TypeError",
  "exception_type": "<class 'TypeError'>",
  "traceback": "Traceback (most recent call last):\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/exception_handler.py\", line 18, in __call__\n    return func(*args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main.py\", line 61, in main_subshell\n    exit_code = do_call(args, parser)\n                ^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/conda_argparse.py\", line 205, in do_call\n    result = getattr(module, func_name)(args, parser)\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main_export.py\", line 129, in execute\n    env.to_dict(stream=fp) if args.json else env.to_yaml(stream=fp)\n    ^^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/env/env.py\", line 253, in to_dict\n    stream.write(json.dumps(d))\nTypeError: a bytes-like object is required, not 'str'\n"
}
```

The traceback in the JSON is

```pytb
Traceback (most recent call last):
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/exception_handler.py", line 18, in __call__
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main.py", line 61, in main_subshell
    exit_code = do_call(args, parser)
                ^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/conda_argparse.py", line 205, in do_call
    result = getattr(module, func_name)(args, parser)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main_export.py", line 129, in execute
    env.to_dict(stream=fp) if args.json else env.to_yaml(stream=fp)
    ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/env/env.py", line 253, in to_dict
    stream.write(json.dumps(d))
TypeError: a bytes-like object is required, not 'str'
```

It looks like `conda env export` is trying to write the JSON to the `--file` argument, rather than YAML, which I think is wrong, but then falling over while trying to do that.

What I would expect is that `conda env export --json --file <>` dumps JSON information to the console but still writes a valid YAML file into `--file`. Am I misusing the option?

### Conda Info

```
     active environment : py312
    active env location : /home/duncan/opt/conda/envs/py312
            shell level : 1
       user config file : /home/duncan/.condarc
 populated config files : /home/duncan/opt/conda/.condarc
                          /home/duncan/.condarc
          conda version : 24.9.1
    conda-build version : 24.7.1
         python version : 3.12.3.final.0
                 solver : libmamba (default)
       virtual packages : __archspec=1=skylake
                          __conda=24.9.1=0
                          __glibc=2.36=0
                          __linux=5.15.153.1=0
                          __unix=0=0
       base environment : /home/duncan/opt/conda  (writable)
      conda av data dir : /home/duncan/opt/conda/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/linux-64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://conda.anaconda.org/igwn/linux-64
                          https://conda.anaconda.org/igwn/noarch
          package cache : /home/duncan/opt/conda/pkgs
                          /home/duncan/.conda/pkgs
       envs directories : /home/duncan/opt/conda/envs
                          /home/duncan/.conda/envs
               platform : linux-64
             user-agent : conda/24.9.1 requests/2.32.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2 debian/12.7 glibc/2.36 solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

```

### Conda Config

```
==> /home/duncan/opt/conda/.condarc <==
channels:
  - conda-forge

==> /home/duncan/.condarc <==
channels:
  - conda-forge
  - igwn
report_errors: False
solver: libmamba

==> envvars <==
allow_softlinks: False
```

### Conda list

```
# packages in environment at /home/duncan/opt/conda/envs/test:
#
# Name                    Version                   Build  Channel
_go_select                2.3.0                       cgo    conda-forge
_libgcc_mutex             0.1                 conda_forge    conda-forge
_openmp_mutex             4.5                       2_gnu    conda-forge
go                        1.23.2               hc4c73a6_0    conda-forge
libgcc                    14.2.0               h77fa898_1    conda-forge
libgfortran               14.2.0               h69a702a_1    conda-forge
libgfortran5              14.2.0               hd5240d6_1    conda-forge
libgomp                   14.2.0               h77fa898_1    conda-forge
libstdcxx                 14.2.0               hc0a3c3a_1    conda-forge
```

### Additional Context

_No response_
conda env export --file=<> --json throws TypeError
### Checklist

- [x] I added a descriptive title
- [x] I searched open reports and couldn't find a duplicate

### What happened?

Attempting to use `conda env export --file=<>` to write a YAML file, whilst at the same time asking for output (progress) to be reported as JSON with `--json` results in a `TypeError`:

To reproduce

```shell
conda create -n test go
conda env export --name test --json --file test.yml
```

Result:

```json
{
  "command": "/home/duncan/opt/conda/bin/conda env export --name test --json --file test.yml",
  "conda_info": {
    "GID": 1000,
    "UID": 1000,
    "active_prefix": "/home/duncan/opt/conda/envs/test",
    "active_prefix_name": "test",
    "av_data_dir": "/home/duncan/opt/conda/etc/conda",
    "av_metadata_url_base": null,
    "channels": [
      "https://conda.anaconda.org/conda-forge/linux-64",
      "https://conda.anaconda.org/conda-forge/noarch",
      "https://conda.anaconda.org/igwn/linux-64",
      "https://conda.anaconda.org/igwn/noarch"
    ],
    "conda_build_version": "24.7.1",
    "conda_env_version": "24.9.1",
    "conda_location": "/home/duncan/opt/conda/lib/python3.12/site-packages/conda",
    "conda_prefix": "/home/duncan/opt/conda",
    "conda_shlvl": 2,
    "conda_version": "24.9.1",
    "config_files": [
      "/home/duncan/opt/conda/.condarc",
      "/home/duncan/.condarc"
    ],
    "default_prefix": "/home/duncan/opt/conda/envs/test",
    "env_vars": {
      "CIO_TEST": "<not set>",
      "CONDA_ALLOW_SOFTLINKS": "false",
      "CONDA_BACKUP_ADDR2LINE": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-addr2line",
      "CONDA_BACKUP_AR": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ar",
      "CONDA_BACKUP_AS": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-as",
      "CONDA_BACKUP_BUILD": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CC": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cc",
      "CONDA_BACKUP_CC_FOR_BUILD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cc",
      "CONDA_BACKUP_CFLAGS": "-march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CMAKE_PREFIX_PATH": "/home/duncan/opt/conda/envs/py312:/home/duncan/opt/conda/envs/py312/x86_64-conda-linux-gnu/sysroot/usr",
      "CONDA_BACKUP_CONDA_BUILD_SYSROOT": "/home/duncan/opt/conda/envs/py312/x86_64-conda-linux-gnu/sysroot",
      "CONDA_BACKUP_CONDA_TOOLCHAIN_BUILD": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CONDA_TOOLCHAIN_HOST": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_CPP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-cpp",
      "CONDA_BACKUP_CPPFLAGS": "-DNDEBUG -D_FORTIFY_SOURCE=2 -O2 -isystem /home/duncan/opt/conda/envs/py312/include -DNDEBUG -D_FORTIFY_SOURCE=2 -O2 -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CXX": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++",
      "CONDA_BACKUP_CXXFILT": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++filt",
      "CONDA_BACKUP_CXXFLAGS": "-fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_CXX_FOR_BUILD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-c++",
      "CONDA_BACKUP_DEBUG_CFLAGS": "-march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DEBUG_CPPFLAGS": "-D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem /home/duncan/opt/conda/envs/py312/include -D_DEBUG -D_FORTIFY_SOURCE=2 -Og -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DEBUG_CXXFLAGS": "-fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include -fvisibility-inlines-hidden -fmessage-length=0 -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-all -fno-plt -Og -g -Wall -Wextra -fvar-tracking-assignments -ffunction-sections -pipe -isystem /home/duncan/opt/conda/envs/py312/include",
      "CONDA_BACKUP_DWP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-dwp",
      "CONDA_BACKUP_ELFEDIT": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-elfedit",
      "CONDA_BACKUP_GCC": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc",
      "CONDA_BACKUP_GCC_AR": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-ar",
      "CONDA_BACKUP_GCC_NM": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-nm",
      "CONDA_BACKUP_GCC_RANLIB": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gcc-ranlib",
      "CONDA_BACKUP_GOROOT": "",
      "CONDA_BACKUP_GPROF": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-gprof",
      "CONDA_BACKUP_GXX": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-g++",
      "CONDA_BACKUP_HOST": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_LD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ld",
      "CONDA_BACKUP_LDFLAGS": "-Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,--allow-shlib-undefined -Wl,-rpath,/home/duncan/opt/conda/envs/py312/lib -Wl,-rpath-link,/home/duncan/opt/conda/envs/py312/lib -L/home/duncan/opt/conda/envs/py312/lib -Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,--allow-shlib-undefined -Wl,-rpath,/home/duncan/opt/conda/envs/py312/lib -Wl,-rpath-link,/home/duncan/opt/conda/envs/py312/lib -L/home/duncan/opt/conda/envs/py312/lib",
      "CONDA_BACKUP_LD_GOLD": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ld.gold",
      "CONDA_BACKUP_MESON_ARGS": "--buildtype release",
      "CONDA_BACKUP_NM": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-nm",
      "CONDA_BACKUP_OBJCOPY": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-objcopy",
      "CONDA_BACKUP_OBJDUMP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-objdump",
      "CONDA_BACKUP_RANLIB": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-ranlib",
      "CONDA_BACKUP_READELF": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-readelf",
      "CONDA_BACKUP_SIZE": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-size",
      "CONDA_BACKUP_STRINGS": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-strings",
      "CONDA_BACKUP_STRIP": "/home/duncan/opt/conda/envs/py312/bin/x86_64-conda-linux-gnu-strip",
      "CONDA_BACKUP__CONDA_PYTHON_SYSCONFIGDATA_NAME": "_sysconfigdata_x86_64_conda_cos6_linux_gnu",
      "CONDA_BACKUP_build_alias": "x86_64-conda-linux-gnu",
      "CONDA_BACKUP_host_alias": "x86_64-conda-linux-gnu",
      "CONDA_DEFAULT_ENV": "test",
      "CONDA_EXE": "/home/duncan/opt/conda/bin/conda",
      "CONDA_PATH": "/home/duncan/opt/conda",
      "CONDA_PREFIX": "/home/duncan/opt/conda/envs/test",
      "CONDA_PREFIX_1": "/home/duncan/opt/conda/envs/py312",
      "CONDA_PROMPT_MODIFIER": "(test) ",
      "CONDA_PYTHON_EXE": "/home/duncan/opt/conda/bin/python",
      "CONDA_ROOT": "/home/duncan/opt/conda",
      "CONDA_SHLVL": "2",
      "CONDA_SMITHY_LOGLEVEL": "DEBUG",
      "CURL_CA_BUNDLE": "<not set>",
      "LD_PRELOAD": "<not set>",
      "MATLABPATH": "/home/duncan/svn/advLigoRTS/trunk/src/epics/simLink:/home/duncan/svn/advLigoRTS/trunk/src/epics/simLink/lib",
      "PATH": "/home/duncan/opt/conda/envs/test/bin:/home/duncan/bin:/home/duncan/opt/conda/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib:/mnt/c/windows/system32:/mnt/c/windows:/mnt/c/windows/System32/Wbem:/mnt/c/windows/System32/WindowsPowerShell/v1.0:/mnt/c/windows/System32/OpenSSH:/mnt/c/Program Files (x86)/Novell/ZENworks/bin:/mnt/c/Program Files/Git/cmd:/mnt/c/Program Files (x86)/GnuPG/bin:/mnt/c/Program Files (x86)/Windows Kits/10/Windows Performance Toolkit:/mnt/c/ProgramData/chocolatey/bin:/mnt/c/Program Files/PowerShell/7:/mnt/c/Program Files/Docker/Docker/resources/bin:/mnt/c/windows/system32/config/systemprofile/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/spxdmm/AppData/Local/Programs/oh-my-posh/bin:/mnt/c/Users/spxdmm/AppData/Local/Programs/Microsoft VS Code/bin:/mnt/c/Program Files/Lens/resources/cli/bin:/mnt/c/Users/spxdmm/AppData/Local/Programs/Lens/resources/cli/bin:/mnt/c/Program Files/Vim/vim91:/home/duncan/bin",
      "PYTHONWARNINGS": ",default::DeprecationWarning,default::PendingDeprecationWarning,ignore:You passed a bytestring:DeprecationWarning,ignore:The SafeConfigParser:DeprecationWarning,ignore:This method will be removed in future versions.  Use 'parser.read_file()' instead:DeprecationWarning,ignore:elementwise != comparison failed; this will raise an error in the future:DeprecationWarning,ignore:the imp module:DeprecationWarning,ignore:metadata:DeprecationWarning,ignore:Using or importing the ABCs:DeprecationWarning,ignore:'U' mode is deprecated,ignore:examples,ignore:The text.latex.unicode,ignore:distutils Version classes are deprecated:DeprecationWarning:requests_mock,ignore:Deprecated call to `pkg_resources:DeprecationWarning,ignore:pkg_resources is deprecated,ignore:conda.:DeprecationWarning,ignore:conda.:PendingDeprecationWarning,ignore:datetime.datetime:DeprecationWarning:boltons.timeutils,ignore:nodes.Node::sphinxcontrib.programoutput",
      "REQUESTS_CA_BUNDLE": "<not set>",
      "SSL_CERT_FILE": "<not set>"
    },
    "envs": [],
    "envs_dirs": [
      "/home/duncan/opt/conda/envs",
      "/home/duncan/.conda/envs"
    ],
    "netrc_file": null,
    "offline": false,
    "pkgs_dirs": [
      "/home/duncan/opt/conda/pkgs",
      "/home/duncan/.conda/pkgs"
    ],
    "platform": "linux-64",
    "python_version": "3.12.3.final.0",
    "rc_path": "/home/duncan/.condarc",
    "requests_version": "2.32.3",
    "root_prefix": "/home/duncan/opt/conda",
    "root_writable": true,
    "site_dirs": [],
    "solver": {
      "default": true,
      "name": "libmamba",
      "user_agent": "solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9"
    },
    "sys.executable": "/home/duncan/opt/conda/bin/python",
    "sys.prefix": "/home/duncan/opt/conda",
    "sys.version": "3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:38:13) [GCC 12.3.0]",
    "sys_rc_path": "/home/duncan/opt/conda/.condarc",
    "user_agent": "conda/24.9.1 requests/2.32.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2 debian/12.7 glibc/2.36 solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9",
    "user_rc_path": "/home/duncan/.condarc",
    "virtual_pkgs": [
      [
        "__archspec",
        "1",
        "skylake"
      ],
      [
        "__conda",
        "24.9.1",
        "0"
      ],
      [
        "__glibc",
        "2.36",
        "0"
      ],
      [
        "__linux",
        "5.15.153.1",
        "0"
      ],
      [
        "__unix",
        "0",
        "0"
      ]
    ]
  },
  "error": "TypeError(\"a bytes-like object is required, not 'str'\")",
  "exception_name": "TypeError",
  "exception_type": "<class 'TypeError'>",
  "traceback": "Traceback (most recent call last):\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/exception_handler.py\", line 18, in __call__\n    return func(*args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main.py\", line 61, in main_subshell\n    exit_code = do_call(args, parser)\n                ^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/conda_argparse.py\", line 205, in do_call\n    result = getattr(module, func_name)(args, parser)\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main_export.py\", line 129, in execute\n    env.to_dict(stream=fp) if args.json else env.to_yaml(stream=fp)\n    ^^^^^^^^^^^^^^^^^^^^^^\n  File \"/home/duncan/opt/conda/lib/python3.12/site-packages/conda/env/env.py\", line 253, in to_dict\n    stream.write(json.dumps(d))\nTypeError: a bytes-like object is required, not 'str'\n"
}
```

The traceback in the JSON is

```pytb
Traceback (most recent call last):
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/exception_handler.py", line 18, in __call__
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main.py", line 61, in main_subshell
    exit_code = do_call(args, parser)
                ^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/conda_argparse.py", line 205, in do_call
    result = getattr(module, func_name)(args, parser)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/cli/main_export.py", line 129, in execute
    env.to_dict(stream=fp) if args.json else env.to_yaml(stream=fp)
    ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/duncan/opt/conda/lib/python3.12/site-packages/conda/env/env.py", line 253, in to_dict
    stream.write(json.dumps(d))
TypeError: a bytes-like object is required, not 'str'
```

It looks like `conda env export` is trying to write the JSON to the `--file` argument, rather than YAML, which I think is wrong, but then falling over while trying to do that.

What I would expect is that `conda env export --json --file <>` dumps JSON information to the console but still writes a valid YAML file into `--file`. Am I misusing the option?

### Conda Info

```
     active environment : py312
    active env location : /home/duncan/opt/conda/envs/py312
            shell level : 1
       user config file : /home/duncan/.condarc
 populated config files : /home/duncan/opt/conda/.condarc
                          /home/duncan/.condarc
          conda version : 24.9.1
    conda-build version : 24.7.1
         python version : 3.12.3.final.0
                 solver : libmamba (default)
       virtual packages : __archspec=1=skylake
                          __conda=24.9.1=0
                          __glibc=2.36=0
                          __linux=5.15.153.1=0
                          __unix=0=0
       base environment : /home/duncan/opt/conda  (writable)
      conda av data dir : /home/duncan/opt/conda/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/linux-64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://conda.anaconda.org/igwn/linux-64
                          https://conda.anaconda.org/igwn/noarch
          package cache : /home/duncan/opt/conda/pkgs
                          /home/duncan/.conda/pkgs
       envs directories : /home/duncan/opt/conda/envs
                          /home/duncan/.conda/envs
               platform : linux-64
             user-agent : conda/24.9.1 requests/2.32.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2 debian/12.7 glibc/2.36 solver/libmamba conda-libmamba-solver/24.7.0 libmambapy/1.5.9
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

```

### Conda Config

```
==> /home/duncan/opt/conda/.condarc <==
channels:
  - conda-forge

==> /home/duncan/.condarc <==
channels:
  - conda-forge
  - igwn
report_errors: False
solver: libmamba

==> envvars <==
allow_softlinks: False
```

### Conda list

```
# packages in environment at /home/duncan/opt/conda/envs/test:
#
# Name                    Version                   Build  Channel
_go_select                2.3.0                       cgo    conda-forge
_libgcc_mutex             0.1                 conda_forge    conda-forge
_openmp_mutex             4.5                       2_gnu    conda-forge
go                        1.23.2               hc4c73a6_0    conda-forge
libgcc                    14.2.0               h77fa898_1    conda-forge
libgfortran               14.2.0               h69a702a_1    conda-forge
libgfortran5              14.2.0               hd5240d6_1    conda-forge
libgomp                   14.2.0               h77fa898_1    conda-forge
libstdcxx                 14.2.0               hc0a3c3a_1    conda-forge
```

### Additional Context

_No response_


Discussion / hints:
@duncanmmacleod,

Your reasoning is sound. I believe this is a bug that we should address.
@duncanmmacleod,

Your reasoning is sound. I believe this is a bug that we should address.

Fix patch:
diff --git a/conda/cli/main_export.py b/conda/cli/main_export.py
index d499e56fee..52e0e6e69f 100644
--- a/conda/cli/main_export.py
+++ b/conda/cli/main_export.py
@@ -115,9 +115,7 @@ def execute(args: Namespace, parser: ArgumentParser) -> int:
     if args.channel is not None:
         env.add_channels(args.channel)
 
-    if args.file is None:
-        stdout_json(env.to_dict()) if args.json else print(env.to_yaml(), end="")
-    else:
+    if args.file:
         filename = args.file
         # check for the proper file extension; otherwise when the export file is used later,
         # the user will get a file parsing error
@@ -125,8 +123,11 @@ def execute(args: Namespace, parser: ArgumentParser) -> int:
             raise CondaValueError(
                 f"Export files must have a valid extension {YAML_EXTENSIONS}: {filename}"
             )
-        fp = open(args.file, "wb")
-        env.to_dict(stream=fp) if args.json else env.to_yaml(stream=fp)
-        fp.close()
+        with open(args.file, "w") as fp:
+            env.to_yaml(stream=fp)
+    if args.json:
+        stdout_json(env.to_dict())
+    else:
+        print(env.to_yaml(), end="")
 
     return 0
diff --git a/news/14323-fix-env-export-file-json b/news/14323-fix-env-export-file-json
new file mode 100644
index 0000000000..0d27d55c5f
--- /dev/null
+++ b/news/14323-fix-env-export-file-json
@@ -0,0 +1,19 @@
+### Enhancements
+
+* <news item>
+
+### Bug fixes
+
+* Fix output writing for `conda export --json --file`. (#14323)
+
+### Deprecations
+
+* <news item>
+
+### Docs
+
+* <news item>
+
+### Other
+
+* <news item>


Test patch:
diff --git a/tests/cli/test_main_export.py b/tests/cli/test_main_export.py
index 73a37c5a39..04e211a5e8 100644
--- a/tests/cli/test_main_export.py
+++ b/tests/cli/test_main_export.py
@@ -11,7 +11,7 @@
 from conda.exceptions import CondaValueError
 
 if TYPE_CHECKING:
-    from pytest import MonkeyPatch
+    from pytest import CaptureFixture, MonkeyPatch
 
     from conda.testing.fixtures import CondaCLIFixture
 
@@ -78,3 +78,19 @@ def test_execute_export_no_file_specified(conda_cli: CondaCLIFixture):
     env_name = "no-file-test"
     conda_cli("export", f"--name={env_name}")
     assert not os.path.exists("env_name" + ".yml")
+
+
+def test_export_with_json(conda_cli: CondaCLIFixture, capsys: CaptureFixture):
+    output = conda_cli(
+        "export",
+        f"--name={TEST_ENV_NAME}",
+        "--json",
+        f"--file={TEST_ENV_NAME}.yml",
+    )
+
+    assert f'"name": "{TEST_ENV_NAME}"' in output[0]
+
+    # Ensure the command executed successfully without any errors
+    assert output[2] == 0
+
+    assert os.path.exists(TEST_ENV_NAME + ".yml")