.. function:: open(file, mode=None)
- If *file* is a string, open the file by that name, otherwise treat it as a
- file-like object. *mode* can be:
+ If *file* is a string, a :term:`path-like object` or a
+ :term:`bytes-like object` open the file by that name, otherwise treat it as
+ a file-like object. *mode* can be:
``'rb'``
Read only mode.
.. versionchanged:: 3.4
Added support for unseekable files.
+ .. versionchanged:: 3.15
+ Added support for :term:`path-like objects <path-like object>`
+ and :term:`bytes-like objects <bytes-like object>`.
+
.. exception:: Error
An error raised when something is impossible because it violates the WAV
import unittest
from test import audiotests
from test import support
+from test.support.os_helper import FakePath
import io
import os
import struct
+import tempfile
import sys
import wave
self.assertIsNone(cm.unraisable)
+class WaveOpen(unittest.TestCase):
+ def test_open_pathlike(self):
+ """It is possible to use `wave.read` and `wave.write` with a path-like object"""
+ with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
+ cases = (
+ FakePath(fp.name),
+ FakePath(os.fsencode(fp.name)),
+ os.fsencode(fp.name),
+ )
+ for fake_path in cases:
+ with self.subTest(fake_path):
+ with wave.open(fake_path, 'wb') as f:
+ f.setnchannels(1)
+ f.setsampwidth(2)
+ f.setframerate(44100)
+
+ with wave.open(fake_path, 'rb') as f:
+ pass
+
+
if __name__ == '__main__':
unittest.main()
from collections import namedtuple
import builtins
+import os
import struct
import sys
def __init__(self, f):
self._i_opened_the_file = None
- if isinstance(f, str):
+ if isinstance(f, (bytes, str, os.PathLike)):
f = builtins.open(f, 'rb')
self._i_opened_the_file = f
# else, assume it is an open file object already
def __init__(self, f):
self._i_opened_the_file = None
- if isinstance(f, str):
+ if isinstance(f, (bytes, str, os.PathLike)):
f = builtins.open(f, 'wb')
self._i_opened_the_file = f
try:
--- /dev/null
+Add support of :term:`path-like objects <path-like object>` and :term:`bytes-like objects <bytes-like object>` in :func:`wave.open`.