We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Turn down logging level for non-existing files in the Python file VSI plugin
To prevent pointless sidecar searching as discussed in https://github.com/rasterio/rasterio/discussions/2825.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rasterio/io.py`
Content:
```
1 """Classes capable of reading and writing datasets
2 
3 Instances of these classes are called dataset objects.
4 """
5 
6 import logging
7 
8 from rasterio._base import get_dataset_driver, driver_can_create, driver_can_create_copy
9 from rasterio._io import (
10     DatasetReaderBase,
11     DatasetWriterBase,
12     BufferedDatasetWriterBase,
13     MemoryFileBase,
14 )
15 from rasterio.windows import WindowMethodsMixin
16 from rasterio.env import ensure_env
17 from rasterio.transform import TransformMethodsMixin
18 from rasterio._path import _UnparsedPath
19 
20 try:
21     from rasterio._filepath import FilePathBase
22 except ImportError:
23     FilePathBase = object
24 
25 
26 log = logging.getLogger(__name__)
27 
28 
29 class DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin):
30     """An unbuffered data and metadata reader"""
31 
32     def __repr__(self):
33         return "<{} DatasetReader name='{}' mode='{}'>".format(
34             self.closed and 'closed' or 'open', self.name, self.mode)
35 
36 
37 class DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin):
38     """An unbuffered data and metadata writer. Its methods write data
39     directly to disk.
40     """
41 
42     def __repr__(self):
43         return "<{} DatasetWriter name='{}' mode='{}'>".format(
44             self.closed and 'closed' or 'open', self.name, self.mode)
45 
46 
47 class BufferedDatasetWriter(
48     BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin
49 ):
50     """Maintains data and metadata in a buffer, writing to disk or
51     network only when `close()` is called.
52 
53     This allows incremental updates to datasets using formats that don't
54     otherwise support updates, such as JPEG.
55     """
56 
57     def __repr__(self):
58         return "<{} BufferedDatasetWriter name='{}' mode='{}'>".format(
59             self.closed and 'closed' or 'open', self.name, self.mode)
60 
61 
62 class MemoryFile(MemoryFileBase):
63     """A BytesIO-like object, backed by an in-memory file.
64 
65     This allows formatted files to be read and written without I/O.
66 
67     A MemoryFile created with initial bytes becomes immutable. A
68     MemoryFile created without initial bytes may be written to using
69     either file-like or dataset interfaces.
70 
71     Examples
72     --------
73 
74     A GeoTIFF can be loaded in memory and accessed using the GeoTIFF
75     format driver
76 
77     >>> with open('tests/data/RGB.byte.tif', 'rb') as f, MemoryFile(f) as memfile:
78     ...     with memfile.open() as src:
79     ...         pprint.pprint(src.profile)
80     ...
81     {'count': 3,
82      'crs': CRS({'init': 'epsg:32618'}),
83      'driver': 'GTiff',
84      'dtype': 'uint8',
85      'height': 718,
86      'interleave': 'pixel',
87      'nodata': 0.0,
88      'tiled': False,
89      'transform': Affine(300.0379266750948, 0.0, 101985.0,
90            0.0, -300.041782729805, 2826915.0),
91      'width': 791}
92 
93     """
94 
95     def __init__(self, file_or_bytes=None, dirname=None, filename=None, ext=".tif"):
96         """Create a new file in memory
97 
98         Parameters
99         ----------
100         file_or_bytes : file-like object or bytes, optional
101             File or bytes holding initial data.
102         filename : str, optional
103             An optional filename. A unique one will otherwise be generated.
104         ext : str, optional
105             An optional extension.
106 
107         Returns
108         -------
109         MemoryFile
110         """
111         super().__init__(
112             file_or_bytes=file_or_bytes, dirname=dirname, filename=filename, ext=ext
113         )
114 
115     @ensure_env
116     def open(self, driver=None, width=None, height=None, count=None, crs=None,
117              transform=None, dtype=None, nodata=None, sharing=False, **kwargs):
118         """Open the file and return a Rasterio dataset object.
119 
120         If data has already been written, the file is opened in 'r'
121         mode. Otherwise, the file is opened in 'w' mode.
122 
123         Parameters
124         ----------
125         Note well that there is no `path` parameter: a `MemoryFile`
126         contains a single dataset and there is no need to specify a
127         path.
128 
129         Other parameters are optional and have the same semantics as the
130         parameters of `rasterio.open()`.
131         """
132         mempath = _UnparsedPath(self.name)
133 
134         if self.closed:
135             raise OSError("I/O operation on closed file.")
136         if len(self) > 0:
137             log.debug("VSI path: {}".format(mempath.path))
138             return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)
139         else:
140             writer = get_writer_for_driver(driver)
141             return writer(
142                 mempath,
143                 "w+",
144                 driver=driver,
145                 width=width,
146                 height=height,
147                 count=count,
148                 crs=crs,
149                 transform=transform,
150                 dtype=dtype,
151                 nodata=nodata,
152                 sharing=sharing,
153                 **kwargs
154             )
155 
156     def __enter__(self):
157         return self
158 
159     def __exit__(self, *args):
160         self.close()
161 
162 
163 class _FilePath(FilePathBase):
164     """A BytesIO-like object, backed by a Python file object.
165 
166     Examples
167     --------
168 
169     A GeoTIFF can be loaded in memory and accessed using the GeoTIFF
170     format driver
171 
172     >>> with open('tests/data/RGB.byte.tif', 'rb') as f, FilePath(f) as vsi_file:
173     ...     with vsi_file.open() as src:
174     ...         pprint.pprint(src.profile)
175     ...
176     {'count': 3,
177      'crs': CRS({'init': 'epsg:32618'}),
178      'driver': 'GTiff',
179      'dtype': 'uint8',
180      'height': 718,
181      'interleave': 'pixel',
182      'nodata': 0.0,
183      'tiled': False,
184      'transform': Affine(300.0379266750948, 0.0, 101985.0,
185            0.0, -300.041782729805, 2826915.0),
186      'width': 791}
187 
188     """
189 
190     def __init__(self, filelike_obj, dirname=None, filename=None):
191         """Create a new wrapper around the provided file-like object.
192 
193         Parameters
194         ----------
195         filelike_obj : file-like object
196             Open file-like object. Currently only reading is supported.
197         filename : str, optional
198             An optional filename. A unique one will otherwise be generated.
199 
200         Returns
201         -------
202         PythonVSIFile
203         """
204         super().__init__(
205             filelike_obj, dirname=dirname, filename=filename
206         )
207 
208     @ensure_env
209     def open(self, driver=None, sharing=False, **kwargs):
210         """Open the file and return a Rasterio dataset object.
211 
212         The provided file-like object is assumed to be readable.
213         Writing is currently not supported.
214 
215         Parameters are optional and have the same semantics as the
216         parameters of `rasterio.open()`.
217         """
218         mempath = _UnparsedPath(self.name)
219 
220         if self.closed:
221             raise IOError("I/O operation on closed file.")
222         # Assume we were given a non-empty file-like object
223         log.debug("VSI path: {}".format(mempath.path))
224         return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)
225 
226     def __enter__(self):
227         return self
228 
229     def __exit__(self, *args):
230         self.close()
231 
232 
233 if FilePathBase is not object:
234     # only make this object available if the cython extension was compiled
235     FilePath = _FilePath
236 
237 
238 class ZipMemoryFile(MemoryFile):
239     """A read-only BytesIO-like object backed by an in-memory zip file.
240 
241     This allows a zip file containing formatted files to be read
242     without I/O.
243     """
244 
245     def __init__(self, file_or_bytes=None):
246         super().__init__(file_or_bytes, ext="zip")
247 
248     @ensure_env
249     def open(self, path, driver=None, sharing=False, **kwargs):
250         """Open a dataset within the zipped stream.
251 
252         Parameters
253         ----------
254         path : str
255             Path to a dataset in the zip file, relative to the root of the
256             archive.
257 
258         Other parameters are optional and have the same semantics as the
259         parameters of `rasterio.open()`.
260 
261         Returns
262         -------
263         A Rasterio dataset object
264         """
265         zippath = _UnparsedPath('/vsizip{0}/{1}'.format(self.name, path.lstrip('/')))
266 
267         if self.closed:
268             raise OSError("I/O operation on closed file.")
269         return DatasetReader(zippath, driver=driver, sharing=sharing, **kwargs)
270 
271 
272 def get_writer_for_driver(driver):
273     """Return the writer class appropriate for the specified driver."""
274     if not driver:
275         raise ValueError("'driver' is required to read/write dataset.")
276     cls = None
277     if driver_can_create(driver):
278         cls = DatasetWriter
279     elif driver_can_create_copy(driver):  # pragma: no branch
280         cls = BufferedDatasetWriter
281     return cls
282 
283 
284 def get_writer_for_path(path, driver=None):
285     """Return the writer class appropriate for the existing dataset."""
286     if not driver:
287         driver = get_dataset_driver(path)
288     return get_writer_for_driver(driver)
289
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/rasterio/io.py b/rasterio/io.py
--- a/rasterio/io.py
+++ b/rasterio/io.py
@@ -13,7 +13,7 @@
     MemoryFileBase,
 )
 from rasterio.windows import WindowMethodsMixin
-from rasterio.env import ensure_env
+from rasterio.env import Env, ensure_env
 from rasterio.transform import TransformMethodsMixin
 from rasterio._path import _UnparsedPath
 
@@ -214,13 +214,25 @@
 
         Parameters are optional and have the same semantics as the
         parameters of `rasterio.open()`.
+
+        Returns
+        -------
+        DatasetReader
+
+        Raises
+        ------
+        IOError
+            If the memory file is closed.
+
         """
         mempath = _UnparsedPath(self.name)
 
         if self.closed:
             raise IOError("I/O operation on closed file.")
+
         # Assume we were given a non-empty file-like object
         log.debug("VSI path: {}".format(mempath.path))
+
         return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)
 
     def __enter__(self):

{"golden_diff": "diff --git a/rasterio/io.py b/rasterio/io.py\n--- a/rasterio/io.py\n+++ b/rasterio/io.py\n@@ -13,7 +13,7 @@\n     MemoryFileBase,\n )\n from rasterio.windows import WindowMethodsMixin\n-from rasterio.env import ensure_env\n+from rasterio.env import Env, ensure_env\n from rasterio.transform import TransformMethodsMixin\n from rasterio._path import _UnparsedPath\n \n@@ -214,13 +214,25 @@\n \n         Parameters are optional and have the same semantics as the\n         parameters of `rasterio.open()`.\n+\n+        Returns\n+        -------\n+        DatasetReader\n+\n+        Raises\n+        ------\n+        IOError\n+            If the memory file is closed.\n+\n         \"\"\"\n         mempath = _UnparsedPath(self.name)\n \n         if self.closed:\n             raise IOError(\"I/O operation on closed file.\")\n+\n         # Assume we were given a non-empty file-like object\n         log.debug(\"VSI path: {}\".format(mempath.path))\n+\n         return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)\n \n     def __enter__(self):\n", "issue": "Turn down logging level for non-existing files in the Python file VSI plugin\nTo prevent pointless sidecar searching as discussed in https://github.com/rasterio/rasterio/discussions/2825.\n", "before_files": [{"content": "\"\"\"Classes capable of reading and writing datasets\n\nInstances of these classes are called dataset objects.\n\"\"\"\n\nimport logging\n\nfrom rasterio._base import get_dataset_driver, driver_can_create, driver_can_create_copy\nfrom rasterio._io import (\n    DatasetReaderBase,\n    DatasetWriterBase,\n    BufferedDatasetWriterBase,\n    MemoryFileBase,\n)\nfrom rasterio.windows import WindowMethodsMixin\nfrom rasterio.env import ensure_env\nfrom rasterio.transform import TransformMethodsMixin\nfrom rasterio._path import _UnparsedPath\n\ntry:\n    from rasterio._filepath import FilePathBase\nexcept ImportError:\n    FilePathBase = object\n\n\nlog = logging.getLogger(__name__)\n\n\nclass DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin):\n    \"\"\"An unbuffered data and metadata reader\"\"\"\n\n    def __repr__(self):\n        return \"<{} DatasetReader name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin):\n    \"\"\"An unbuffered data and metadata writer. Its methods write data\n    directly to disk.\n    \"\"\"\n\n    def __repr__(self):\n        return \"<{} DatasetWriter name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass BufferedDatasetWriter(\n    BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin\n):\n    \"\"\"Maintains data and metadata in a buffer, writing to disk or\n    network only when `close()` is called.\n\n    This allows incremental updates to datasets using formats that don't\n    otherwise support updates, such as JPEG.\n    \"\"\"\n\n    def __repr__(self):\n        return \"<{} BufferedDatasetWriter name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass MemoryFile(MemoryFileBase):\n    \"\"\"A BytesIO-like object, backed by an in-memory file.\n\n    This allows formatted files to be read and written without I/O.\n\n    A MemoryFile created with initial bytes becomes immutable. A\n    MemoryFile created without initial bytes may be written to using\n    either file-like or dataset interfaces.\n\n    Examples\n    --------\n\n    A GeoTIFF can be loaded in memory and accessed using the GeoTIFF\n    format driver\n\n    >>> with open('tests/data/RGB.byte.tif', 'rb') as f, MemoryFile(f) as memfile:\n    ...     with memfile.open() as src:\n    ...         pprint.pprint(src.profile)\n    ...\n    {'count': 3,\n     'crs': CRS({'init': 'epsg:32618'}),\n     'driver': 'GTiff',\n     'dtype': 'uint8',\n     'height': 718,\n     'interleave': 'pixel',\n     'nodata': 0.0,\n     'tiled': False,\n     'transform': Affine(300.0379266750948, 0.0, 101985.0,\n           0.0, -300.041782729805, 2826915.0),\n     'width': 791}\n\n    \"\"\"\n\n    def __init__(self, file_or_bytes=None, dirname=None, filename=None, ext=\".tif\"):\n        \"\"\"Create a new file in memory\n\n        Parameters\n        ----------\n        file_or_bytes : file-like object or bytes, optional\n            File or bytes holding initial data.\n        filename : str, optional\n            An optional filename. A unique one will otherwise be generated.\n        ext : str, optional\n            An optional extension.\n\n        Returns\n        -------\n        MemoryFile\n        \"\"\"\n        super().__init__(\n            file_or_bytes=file_or_bytes, dirname=dirname, filename=filename, ext=ext\n        )\n\n    @ensure_env\n    def open(self, driver=None, width=None, height=None, count=None, crs=None,\n             transform=None, dtype=None, nodata=None, sharing=False, **kwargs):\n        \"\"\"Open the file and return a Rasterio dataset object.\n\n        If data has already been written, the file is opened in 'r'\n        mode. Otherwise, the file is opened in 'w' mode.\n\n        Parameters\n        ----------\n        Note well that there is no `path` parameter: a `MemoryFile`\n        contains a single dataset and there is no need to specify a\n        path.\n\n        Other parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n        \"\"\"\n        mempath = _UnparsedPath(self.name)\n\n        if self.closed:\n            raise OSError(\"I/O operation on closed file.\")\n        if len(self) > 0:\n            log.debug(\"VSI path: {}\".format(mempath.path))\n            return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)\n        else:\n            writer = get_writer_for_driver(driver)\n            return writer(\n                mempath,\n                \"w+\",\n                driver=driver,\n                width=width,\n                height=height,\n                count=count,\n                crs=crs,\n                transform=transform,\n                dtype=dtype,\n                nodata=nodata,\n                sharing=sharing,\n                **kwargs\n            )\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n\nclass _FilePath(FilePathBase):\n    \"\"\"A BytesIO-like object, backed by a Python file object.\n\n    Examples\n    --------\n\n    A GeoTIFF can be loaded in memory and accessed using the GeoTIFF\n    format driver\n\n    >>> with open('tests/data/RGB.byte.tif', 'rb') as f, FilePath(f) as vsi_file:\n    ...     with vsi_file.open() as src:\n    ...         pprint.pprint(src.profile)\n    ...\n    {'count': 3,\n     'crs': CRS({'init': 'epsg:32618'}),\n     'driver': 'GTiff',\n     'dtype': 'uint8',\n     'height': 718,\n     'interleave': 'pixel',\n     'nodata': 0.0,\n     'tiled': False,\n     'transform': Affine(300.0379266750948, 0.0, 101985.0,\n           0.0, -300.041782729805, 2826915.0),\n     'width': 791}\n\n    \"\"\"\n\n    def __init__(self, filelike_obj, dirname=None, filename=None):\n        \"\"\"Create a new wrapper around the provided file-like object.\n\n        Parameters\n        ----------\n        filelike_obj : file-like object\n            Open file-like object. Currently only reading is supported.\n        filename : str, optional\n            An optional filename. A unique one will otherwise be generated.\n\n        Returns\n        -------\n        PythonVSIFile\n        \"\"\"\n        super().__init__(\n            filelike_obj, dirname=dirname, filename=filename\n        )\n\n    @ensure_env\n    def open(self, driver=None, sharing=False, **kwargs):\n        \"\"\"Open the file and return a Rasterio dataset object.\n\n        The provided file-like object is assumed to be readable.\n        Writing is currently not supported.\n\n        Parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n        \"\"\"\n        mempath = _UnparsedPath(self.name)\n\n        if self.closed:\n            raise IOError(\"I/O operation on closed file.\")\n        # Assume we were given a non-empty file-like object\n        log.debug(\"VSI path: {}\".format(mempath.path))\n        return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n\nif FilePathBase is not object:\n    # only make this object available if the cython extension was compiled\n    FilePath = _FilePath\n\n\nclass ZipMemoryFile(MemoryFile):\n    \"\"\"A read-only BytesIO-like object backed by an in-memory zip file.\n\n    This allows a zip file containing formatted files to be read\n    without I/O.\n    \"\"\"\n\n    def __init__(self, file_or_bytes=None):\n        super().__init__(file_or_bytes, ext=\"zip\")\n\n    @ensure_env\n    def open(self, path, driver=None, sharing=False, **kwargs):\n        \"\"\"Open a dataset within the zipped stream.\n\n        Parameters\n        ----------\n        path : str\n            Path to a dataset in the zip file, relative to the root of the\n            archive.\n\n        Other parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n\n        Returns\n        -------\n        A Rasterio dataset object\n        \"\"\"\n        zippath = _UnparsedPath('/vsizip{0}/{1}'.format(self.name, path.lstrip('/')))\n\n        if self.closed:\n            raise OSError(\"I/O operation on closed file.\")\n        return DatasetReader(zippath, driver=driver, sharing=sharing, **kwargs)\n\n\ndef get_writer_for_driver(driver):\n    \"\"\"Return the writer class appropriate for the specified driver.\"\"\"\n    if not driver:\n        raise ValueError(\"'driver' is required to read/write dataset.\")\n    cls = None\n    if driver_can_create(driver):\n        cls = DatasetWriter\n    elif driver_can_create_copy(driver):  # pragma: no branch\n        cls = BufferedDatasetWriter\n    return cls\n\n\ndef get_writer_for_path(path, driver=None):\n    \"\"\"Return the writer class appropriate for the existing dataset.\"\"\"\n    if not driver:\n        driver = get_dataset_driver(path)\n    return get_writer_for_driver(driver)\n", "path": "rasterio/io.py"}], "after_files": [{"content": "\"\"\"Classes capable of reading and writing datasets\n\nInstances of these classes are called dataset objects.\n\"\"\"\n\nimport logging\n\nfrom rasterio._base import get_dataset_driver, driver_can_create, driver_can_create_copy\nfrom rasterio._io import (\n    DatasetReaderBase,\n    DatasetWriterBase,\n    BufferedDatasetWriterBase,\n    MemoryFileBase,\n)\nfrom rasterio.windows import WindowMethodsMixin\nfrom rasterio.env import Env, ensure_env\nfrom rasterio.transform import TransformMethodsMixin\nfrom rasterio._path import _UnparsedPath\n\ntry:\n    from rasterio._filepath import FilePathBase\nexcept ImportError:\n    FilePathBase = object\n\n\nlog = logging.getLogger(__name__)\n\n\nclass DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin):\n    \"\"\"An unbuffered data and metadata reader\"\"\"\n\n    def __repr__(self):\n        return \"<{} DatasetReader name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin):\n    \"\"\"An unbuffered data and metadata writer. Its methods write data\n    directly to disk.\n    \"\"\"\n\n    def __repr__(self):\n        return \"<{} DatasetWriter name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass BufferedDatasetWriter(\n    BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin\n):\n    \"\"\"Maintains data and metadata in a buffer, writing to disk or\n    network only when `close()` is called.\n\n    This allows incremental updates to datasets using formats that don't\n    otherwise support updates, such as JPEG.\n    \"\"\"\n\n    def __repr__(self):\n        return \"<{} BufferedDatasetWriter name='{}' mode='{}'>\".format(\n            self.closed and 'closed' or 'open', self.name, self.mode)\n\n\nclass MemoryFile(MemoryFileBase):\n    \"\"\"A BytesIO-like object, backed by an in-memory file.\n\n    This allows formatted files to be read and written without I/O.\n\n    A MemoryFile created with initial bytes becomes immutable. A\n    MemoryFile created without initial bytes may be written to using\n    either file-like or dataset interfaces.\n\n    Examples\n    --------\n\n    A GeoTIFF can be loaded in memory and accessed using the GeoTIFF\n    format driver\n\n    >>> with open('tests/data/RGB.byte.tif', 'rb') as f, MemoryFile(f) as memfile:\n    ...     with memfile.open() as src:\n    ...         pprint.pprint(src.profile)\n    ...\n    {'count': 3,\n     'crs': CRS({'init': 'epsg:32618'}),\n     'driver': 'GTiff',\n     'dtype': 'uint8',\n     'height': 718,\n     'interleave': 'pixel',\n     'nodata': 0.0,\n     'tiled': False,\n     'transform': Affine(300.0379266750948, 0.0, 101985.0,\n           0.0, -300.041782729805, 2826915.0),\n     'width': 791}\n\n    \"\"\"\n\n    def __init__(self, file_or_bytes=None, dirname=None, filename=None, ext=\".tif\"):\n        \"\"\"Create a new file in memory\n\n        Parameters\n        ----------\n        file_or_bytes : file-like object or bytes, optional\n            File or bytes holding initial data.\n        filename : str, optional\n            An optional filename. A unique one will otherwise be generated.\n        ext : str, optional\n            An optional extension.\n\n        Returns\n        -------\n        MemoryFile\n        \"\"\"\n        super().__init__(\n            file_or_bytes=file_or_bytes, dirname=dirname, filename=filename, ext=ext\n        )\n\n    @ensure_env\n    def open(self, driver=None, width=None, height=None, count=None, crs=None,\n             transform=None, dtype=None, nodata=None, sharing=False, **kwargs):\n        \"\"\"Open the file and return a Rasterio dataset object.\n\n        If data has already been written, the file is opened in 'r'\n        mode. Otherwise, the file is opened in 'w' mode.\n\n        Parameters\n        ----------\n        Note well that there is no `path` parameter: a `MemoryFile`\n        contains a single dataset and there is no need to specify a\n        path.\n\n        Other parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n        \"\"\"\n        mempath = _UnparsedPath(self.name)\n\n        if self.closed:\n            raise OSError(\"I/O operation on closed file.\")\n        if len(self) > 0:\n            log.debug(\"VSI path: {}\".format(mempath.path))\n            return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)\n        else:\n            writer = get_writer_for_driver(driver)\n            return writer(\n                mempath,\n                \"w+\",\n                driver=driver,\n                width=width,\n                height=height,\n                count=count,\n                crs=crs,\n                transform=transform,\n                dtype=dtype,\n                nodata=nodata,\n                sharing=sharing,\n                **kwargs\n            )\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n\nclass _FilePath(FilePathBase):\n    \"\"\"A BytesIO-like object, backed by a Python file object.\n\n    Examples\n    --------\n\n    A GeoTIFF can be loaded in memory and accessed using the GeoTIFF\n    format driver\n\n    >>> with open('tests/data/RGB.byte.tif', 'rb') as f, FilePath(f) as vsi_file:\n    ...     with vsi_file.open() as src:\n    ...         pprint.pprint(src.profile)\n    ...\n    {'count': 3,\n     'crs': CRS({'init': 'epsg:32618'}),\n     'driver': 'GTiff',\n     'dtype': 'uint8',\n     'height': 718,\n     'interleave': 'pixel',\n     'nodata': 0.0,\n     'tiled': False,\n     'transform': Affine(300.0379266750948, 0.0, 101985.0,\n           0.0, -300.041782729805, 2826915.0),\n     'width': 791}\n\n    \"\"\"\n\n    def __init__(self, filelike_obj, dirname=None, filename=None):\n        \"\"\"Create a new wrapper around the provided file-like object.\n\n        Parameters\n        ----------\n        filelike_obj : file-like object\n            Open file-like object. Currently only reading is supported.\n        filename : str, optional\n            An optional filename. A unique one will otherwise be generated.\n\n        Returns\n        -------\n        PythonVSIFile\n        \"\"\"\n        super().__init__(\n            filelike_obj, dirname=dirname, filename=filename\n        )\n\n    @ensure_env\n    def open(self, driver=None, sharing=False, **kwargs):\n        \"\"\"Open the file and return a Rasterio dataset object.\n\n        The provided file-like object is assumed to be readable.\n        Writing is currently not supported.\n\n        Parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n\n        Returns\n        -------\n        DatasetReader\n\n        Raises\n        ------\n        IOError\n            If the memory file is closed.\n\n        \"\"\"\n        mempath = _UnparsedPath(self.name)\n\n        if self.closed:\n            raise IOError(\"I/O operation on closed file.\")\n\n        # Assume we were given a non-empty file-like object\n        log.debug(\"VSI path: {}\".format(mempath.path))\n\n        return DatasetReader(mempath, driver=driver, sharing=sharing, **kwargs)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n\nif FilePathBase is not object:\n    # only make this object available if the cython extension was compiled\n    FilePath = _FilePath\n\n\nclass ZipMemoryFile(MemoryFile):\n    \"\"\"A read-only BytesIO-like object backed by an in-memory zip file.\n\n    This allows a zip file containing formatted files to be read\n    without I/O.\n    \"\"\"\n\n    def __init__(self, file_or_bytes=None):\n        super().__init__(file_or_bytes, ext=\"zip\")\n\n    @ensure_env\n    def open(self, path, driver=None, sharing=False, **kwargs):\n        \"\"\"Open a dataset within the zipped stream.\n\n        Parameters\n        ----------\n        path : str\n            Path to a dataset in the zip file, relative to the root of the\n            archive.\n\n        Other parameters are optional and have the same semantics as the\n        parameters of `rasterio.open()`.\n\n        Returns\n        -------\n        A Rasterio dataset object\n        \"\"\"\n        zippath = _UnparsedPath('/vsizip{0}/{1}'.format(self.name, path.lstrip('/')))\n\n        if self.closed:\n            raise OSError(\"I/O operation on closed file.\")\n        return DatasetReader(zippath, driver=driver, sharing=sharing, **kwargs)\n\n\ndef get_writer_for_driver(driver):\n    \"\"\"Return the writer class appropriate for the specified driver.\"\"\"\n    if not driver:\n        raise ValueError(\"'driver' is required to read/write dataset.\")\n    cls = None\n    if driver_can_create(driver):\n        cls = DatasetWriter\n    elif driver_can_create_copy(driver):  # pragma: no branch\n        cls = BufferedDatasetWriter\n    return cls\n\n\ndef get_writer_for_path(path, driver=None):\n    \"\"\"Return the writer class appropriate for the existing dataset.\"\"\"\n    if not driver:\n        driver = get_dataset_driver(path)\n    return get_writer_for_driver(driver)\n", "path": "rasterio/io.py"}]}