diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index ade87c4215a38..ce16c8ced28b9 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -572,6 +572,7 @@ I/O - Bug in :meth:`DataFrame.to_hdf` and :func:`read_hdf` with ``datetime64`` dtypes with non-nanosecond resolution failing to round-trip correctly (:issue:`55622`) - Bug in :meth:`pandas.read_excel` with ``engine="odf"`` (``ods`` files) when string contains annotation (:issue:`55200`) - Bug in :meth:`pandas.read_excel` with an ODS file without cached formatted cell for float values (:issue:`55219`) +- Bug where :meth:`DataFrame.to_csv` would raise a ``URLError`` when specifying local file scheme paths to not-yet-created files (:issue:`55828`) - Bug where :meth:`DataFrame.to_json` would raise an ``OverflowError`` instead of a ``TypeError`` with unsupported NumPy types (:issue:`55403`) Period diff --git a/pandas/io/common.py b/pandas/io/common.py index d08612f4f09f6..d65b0c8bcb77b 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -382,6 +382,19 @@ def _get_filepath_or_buffer( # urlopen function defined elsewhere in this module import urllib.request + # Fix for GH #55828 + parsed_url = parse_url(filepath_or_buffer) + if parsed_url.scheme == "file": + file_path = urllib.request.url2pathname(parsed_url.path) + file_path = os.path.normpath(file_path) + return IOArgs( + filepath_or_buffer=open(file_path, "rb"), + encoding=encoding, + compression=compression, + should_close=True, + mode=fsspec_mode, + ) + # assuming storage_options is to be interpreted as headers req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options) with urlopen(req_info) as req: