Python pathlib.WindowsPath() Examples

The following are 19 code examples of pathlib.WindowsPath(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pathlib , or try the search function .
Example #1
Source File: py7zr.py    From py7zr with GNU Lesser General Public License v2.1 6 votes vote down vote up
def is_7zfile(file: Union[BinaryIO, str, pathlib.Path]) -> bool:
    """Quickly see if a file is a 7Z file by checking the magic number.
    The file argument may be a filename or file-like object too.
    """
    result = False
    try:
        if isinstance(file, io.IOBase) and hasattr(file, "read"):
            result = SevenZipFile._check_7zfile(file)  # type: ignore  # noqa
        elif isinstance(file, str):
            with open(file, 'rb') as fp:
                result = SevenZipFile._check_7zfile(fp)
        elif isinstance(file, pathlib.Path) or isinstance(file, pathlib.PosixPath) or \
                isinstance(file, pathlib.WindowsPath):
            with file.open(mode='rb') as fp:  # type: ignore  # noqa
                result = SevenZipFile._check_7zfile(fp)
        else:
            raise TypeError('invalid type: file should be str, pathlib.Path or BinaryIO, but {}'.format(type(file)))
    except OSError:
        pass
    return result 
Example #2
Source File: test_win32compat.py    From py7zr with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_symlink_readlink_absolute(tmp_path):
    origin = tmp_path / 'parent' / 'original.txt'
    origin.parent.mkdir(parents=True, exist_ok=True)
    with origin.open('w') as f:
        f.write("Original")
    slink = tmp_path / "target" / "link"
    slink.parent.mkdir(parents=True, exist_ok=True)
    target = origin.resolve()
    slink.symlink_to(target, False)
    if sys.platform.startswith("win"):
        assert py7zr.win32compat.readlink(str(tmp_path / "target" / "link")) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(str(slink)) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(slink) == pathlib.WindowsPath(PATH_PREFIX + str(target))
    else:
        assert py7zr.helpers.readlink(str(slink)) == str(target)
        assert py7zr.helpers.readlink(slink) == target
    assert slink.open('r').read() == 'Original' 
Example #3
Source File: test_win32compat.py    From py7zr with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_junction_readlink(tmp_path):
    target = tmp_path / 'parent'
    target.mkdir(parents=True, exist_ok=True)
    with target.joinpath("original.txt").open('w') as f:
        f.write("Original")
    junction = tmp_path / "target" / "link"
    junction.parent.mkdir(parents=True, exist_ok=True)
    os.system('mklink /J %s %s' % (str(junction), str(target.resolve())))
    assert not os.path.islink(str(junction))
    assert py7zr.win32compat.is_reparse_point(str(junction))
    assert py7zr.win32compat.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.helpers.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.win32compat.is_reparse_point(junction)
    assert py7zr.win32compat.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve()))
    assert py7zr.helpers.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve())) 
Example #4
Source File: test_pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
Example #5
Source File: test_pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
Example #6
Source File: _logging.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_file_logger(filename: str, level: Union[str, int] = 0) -> None:
    """Set logging level and filename for the file handler."""
    try:
        filename = pathlib.Path(filename)
    except NotImplementedError:
        filename = pathlib.WindowsPath(filename)

    file_handler = logging.FileHandler(filename)
    file_handler.setFormatter(log_formatter)
    file_handler.set_name("FileLogger")
    logger.addHandler(file_handler)
    _setLevel(file_handler, level) 
Example #7
Source File: utils.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def _check_filename(value) -> Union[pathlib.Path, pathlib.WindowsPath]:
    if not isinstance(value, (pathlib.Path, pathlib.WindowsPath)):
        try:
            return pathlib.Path(value)
        except NotImplementedError:
            return pathlib.WindowsPath(value)
        except:
            raise Exception("File error") 
Example #8
Source File: aescipher.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def detect_file_encryption(filename: Union[pathlib.Path, pathlib.WindowsPath]):
    file = filename.read_bytes()
    try:
        file = json.loads(file)
        if "adp_token" in file:
            return False
        elif "ciphertext" in file:
            return "json"
    except UnicodeDecodeError:
        return "bytes" 
Example #9
Source File: aescipher.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def from_file(self, filename: Union[pathlib.Path, pathlib.WindowsPath],
                  encryption="json"):
        if encryption == "json":
            encrypted_json = filename.read_text()
            encrypted_dict = json.loads(encrypted_json)

            return self.from_dict(encrypted_dict)

        elif encryption == "bytes":
            encrypted_data = filename.read_bytes()
    
            return self.from_bytes(encrypted_data)

        else:
            raise ValueError("encryption must be \"json\" or \"bytes\".") 
Example #10
Source File: aescipher.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def to_file(self, data: str,
                filename: Union[pathlib.Path, pathlib.WindowsPath],
                encryption="json", indent=4):
        if encryption == "json":
            encrypted_dict = self.to_dict(data)
            data_json = json.dumps(encrypted_dict, indent=indent)
            filename.write_text(data_json)

        elif encryption == "bytes":
            encrypted_data = self.to_bytes(data)
            filename.write_bytes(encrypted_data)

        else:
            raise ValueError("encryption must be \"json\" or \"bytes\"..") 
Example #11
Source File: targets.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, path=None, name=None, suffix=None, prefix=None, dir=None):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        filename = request_answer_from_controller(
            ['sos_tempfile', path, name, suffix, prefix, dir])
        return cls._from_parts([filename]) 
Example #12
Source File: targets.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        return cls._from_parts(args).expanduser().expandnamed(
            host=kwargs.get('host', None)) 
Example #13
Source File: test_pathlib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
Example #14
Source File: test_pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
Example #15
Source File: test_pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
Example #16
Source File: help_functions.py    From TextileDefectDetection with GNU Affero General Public License v3.0 5 votes vote down vote up
def getStem(name):
    target_name = None

    if platform.system() == 'Windows':
        target_name = WindowsPath(name).stem
    elif platform.system() == 'Linux':
        target_name = PosixPath(name).stem
    else:
        print("Operation System: " + str(platform.system()) + ", unfortunately not supported here")
        raise Exception('Unknown OS: ' + platform.system())

    return target_name 
Example #17
Source File: test_pathlib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
Example #18
Source File: test_pathlib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
Example #19
Source File: test_pathlib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath)