{"record":{"id":"5a9849d10e535735","repo":"pytest-dev/pytest","slug":"can-only-process-bytes","errorCode":null,"errorMessage":"can only process bytes","messagePattern":"can only process bytes","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/_pytest/_py/path.py","lineNumber":918,"sourceCode":"\n    def write_text(self, data, encoding, ensure=False):\n        \"\"\"Write text data into path using the specified encoding.\n        If ensure is True create missing parent directories.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        with self.open(\"w\", encoding=encoding) as f:\n            f.write(data)\n\n    def write(self, data, mode=\"w\", ensure=False):\n        \"\"\"Write data into path.   If ensure is True create\n        missing parent directories.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        if \"b\" in mode:\n            if not isinstance(data, bytes):\n                raise ValueError(\"can only process bytes\")\n        else:\n            if not isinstance(data, str):\n                if not isinstance(data, bytes):\n                    data = str(data)\n                else:\n                    data = data.decode(sys.getdefaultencoding())\n        f = self.open(mode)\n        try:\n            f.write(data)\n        finally:\n            f.close()\n\n    def _ensuredirs(self):\n        parent = self.dirpath()\n        if parent == self:\n            return self\n        if parent.check(dir=0):\n            parent._ensuredirs()","sourceCodeStart":900,"sourceCodeEnd":936,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/_py/path.py#L900-L936","documentation":"Raised by LocalPath.write() when the mode string contains 'b' (binary mode) but the supplied data is not a bytes object. The method enforces a strict contract: binary write requires bytes input, text write accepts str (and coerces other types via str()). Supplying a str to a binary-mode write triggers this ValueError before any file handle is opened.","triggerScenarios":"Calling path.write('hello', mode='wb'); calling path.write(some_object, mode='wb') where the object is not bytes.","commonSituations":"Pickling/serializing to a path and forgetting to encode; porting code that wrote text in binary mode; mixing up data types when writing generated artifacts or snapshots.","solutions":["If writing text, use mode='w' (the default) or encode first: path.write('hello'.encode('utf-8'), mode='wb').","If you have bytes, ensure mode includes 'b'.","Use pathlib.Path.write_bytes / write_text for clearer intent."],"exampleFix":"// before\np.write('hello', mode='wb')\n// after\np.write('hello', mode='w')","handlingStrategy":"type-guard","validationCode":"def safe_write(path, data, mode='w', ensure=False):\n    if 'b' in mode:\n        assert isinstance(data, bytes), 'binary mode requires bytes'\n    path.write(data, mode=mode, ensure=ensure)","typeGuard":"def is_bytes_for_binary(data, mode: str) -> bool:\n    return 'b' not in mode or isinstance(data, bytes)","tryCatchPattern":null,"preventionTips":["Match data type to mode: bytes<->'b', str<->'w'.","Prefer pathlib.Path.write_text / write_bytes to make intent explicit."],"tags":["py-path","localpath","io","type-mismatch"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}