我正在努力解决Python 3.6中Pathlib模块的Path.glob()方法的结果.
from pathlib import Path
dir = Path.cwd()
files = dir.glob('*.txt')
print(list(files))
>> [WindowsPath('C:/whatever/file1.txt'), WindowsPath('C:/whatever/file2.txt')]
for file in files:
print(file)
print('Check.')
>>
Run Code Online (Sandbox Code Playgroud)
显然,glob找到了文件,但是没有执行for循环.如何循环pathlib-glob-search的结果?
根据 python 3.6 文档,可以通过以下方式创建目录:
pathlib.Path.mkdir(mode=0o777, parents=False, exist_ok=False)
os.mkdir(path, mode=0o777, *, dir_fd=None)
os.makedirs(name, mode=0o777, exist_ok=False)
问题:
pathlib.Path.mkdir()
做了大部分什么os.mkdir()
和os.makedirs()
做什么。是pathlib.Path.mkdir()
一个“现代”的实施两者的os.mkdir()
和os.makedirs()
?pathlib.Path.mkdir()
vsos.mkdir()
或os.makedirs()
? 有什么性能差异吗?请解释有关 POSIX 的注意事项。谢谢。
是否有 Pathlib 等价物os.access()
?
如果没有 Pathlib,代码将如下所示:
import os
os.access('my_folder', os.R_OK) # check if script has read access to folder
Run Code Online (Sandbox Code Playgroud)
但是,在我的代码中,我正在处理 Pathlib 路径,因此我需要这样做(这只是一个示例):
# Python 3.5+
from pathlib import Path
import os
# get path ~/home/github if on Linux
my_folder_pathlib = Path.home() / "github"
os.access(str(my_folder_pathlib), os.R_OK)
Run Code Online (Sandbox Code Playgroud)
演员str()
阵容有点丑。我想知道我想要实现的目标是否有纯 Pathlib 解决方案?
ps 我知道“更容易请求宽恕”的原则,但是这是一个更大框架的一部分,我需要尽快知道脚本是否具有对 NAS 存储文件夹的正确权限。
我想找到具有两种不同扩展名的两种类型的文件:.jl
和.jsonlines
. 我用
from pathlib import Path
p1 = Path("/path/to/dir").joinpath().glob("*.jl")
p2 = Path("/path/to/dir").joinpath().glob("*.jsonlines")
Run Code Online (Sandbox Code Playgroud)
但我想要p1
和p2
作为一个变量而不是两个。我应该合并p1
,并p2
在首位?还有其他方法可以连接 glob 的模式吗?
当我有一个pd.DataFrame
with 路径时,我最终做了很多.map(lambda path: Path(path).{method_name}
,或者apply(axis=1)
例如:
(
pd.DataFrame({'base_dir': ['dir_A', 'dir_B'], 'file_name': ['file_0', 'file_1']})
.assign(full_path=lambda df: df.apply(lambda row: Path(row.base_dir) / row.file_name, axis=1))
)
base_dir file_name full_path
0 dir_A file_0 dir_A/file_0
1 dir_B file_1 dir_B/file_1
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很奇怪,尤其是因为pathlib
确实实现了,/
所以类似的东西df.base_dir / df.file_name
会更加 Pythonic 和自然。
我还没有找到path
在 Pandas 中实现的任何类型,有什么我遗漏的吗?
我发现最好一次做一次,astype(path)
然后至少对路径连接进行pathlib
矢量化:
(
pd.DataFrame({'base_dir': ['dir_A', 'dir_B'], 'file_name': ['file_0', 'file_1']})
# this is where I would expect `astype({'base_dir': Path})`
.assign(**{col_name:lambda df: df[col_name].map(Path) for col_name …
Run Code Online (Sandbox Code Playgroud) 我需要创建一个以当前目录开头的相对路径“.” 点
例如,在 Windows 中“.\envs\.some.env”或其他地方的“./envs/.some.env”
我想使用 pathlib 来做到这一点。找到了解决方案,但它有一个笨拙的替换语句。有没有更好的方法使用 pathlib 来做到这一点?
用法是 django-environ,目标是支持多个 env 文件。工作文件夹包含一个 envs 文件夹,该文件夹中包含多个 env 文件。
import environ
from pathlib import Path
import os
domain_env = Path.cwd()
dotdot = Path("../")
some_env = dotdot / "envs" / ".some.env"
envsome = environ.Env()
envsome.read_env(envsome.str(str(domain_env), str(some_env).replace("..", ".")))
print(str(some_env))
print(str(some_env).replace("..", "."))
dot = Path("./") # Path(".") gives the same result
some_env = dot / "envs" / ".some.env"
print(str(some_env))
Run Code Online (Sandbox Code Playgroud)
在 Windows 上给出:
..\envs\.some.env
.\envs\.some.env
envs\.some.env
Run Code Online (Sandbox Code Playgroud) 如何使用pathlib输出带有正斜杠的路径?我经常遇到只接受带有正斜杠的路径的程序,但我不知道如何让 pathlib 为我做到这一点。
from pathlib import Path, PurePosixPath
native = Path('c:/scratch/test.vim')
print(str(native))
# Out: c:\scratch\test.vim
# Backslashes as expected.
posix = PurePosixPath(str(native))
print(str(posix))
# Out: c:\scratch\test.vim
# Why backslashes again?
posix = PurePosixPath('c:/scratch/test.vim')
print(str(posix))
# Out: c:/scratch/test.vim
# Works, but only because I never used a Path object
posix = PurePosixPath(str(native))
print(str(posix).replace('\\', '/'))
# Out: c:/scratch/test.vim
# Works, but ugly and may cause bugs
Run Code Online (Sandbox Code Playgroud)
PurePosixPath
pathlib 中没有unlink
、glob
、 和其他有用的实用程序,因此我不能专门使用它。PosixPath
在 Windows 上抛出 NotImplementedError。
这是必要的实际用例:zipfile.ZipFile
需要正斜杠,但在给定反斜杠时无法匹配路径。 …
下面的代码是我首先尝试的,但some_path.with_suffix('.jpg')
显然返回一个pathlib.PosixPath
对象(我在Linux上)而不是我的版本PosixPath
,因为我没有重新定义with_suffix
.我是否必须复制所有内容pathlib
或有更好的方法吗?
import os
import pathlib
from shutil import rmtree
class Path(pathlib.Path):
def __new__(cls, *args, **kwargs):
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
self = cls._from_parts(args, init=False)
if not self._flavour.is_supported:
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
self._init()
return self
def with_stem(self, stem):
"""
Return a new path with the stem changed.
The stem is the final path component, minus its last suffix. …
Run Code Online (Sandbox Code Playgroud) 我有一个位于两个目录下的脚本。
\n\xe2\x9d\xaf tree\n.\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 foo\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 bar\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 test.py\n\xe2\x9d\xaf cd foo/bar\n\xe2\x9d\xaf cat test.py\n\n from pathlib import Path\n print(Path(__file__).parent)\n print(Path(__file__).parent.parent)\n
Run Code Online (Sandbox Code Playgroud)\n当我从包含该文件的目录运行它时,PathLib 认为该文件的祖父与其父级相同。
\n\xe2\x9d\xaf python test.py\n\n . # <-- same\n . # <-- directories\n
Run Code Online (Sandbox Code Playgroud)\n但是当我从顶层运行它时,PathLib 行为正确。
\n\xe2\x9d\xaf cd ../..\n\xe2\x9d\xaf python foo/bar/test.py\n\n foo/bar # <-- different\n foo # <-- directories\n
Run Code Online (Sandbox Code Playgroud)\n我是否误解了 PathLib 的 API,或者是否有其他原因导致其输出对我的工作目录敏感?
\n我想找到所有图像并尝试使用 pathlib,但我的 reg 表达式不起作用。我哪里错了?
from pathlib import Path
FILE_PATHS=list(Path('./photos/test').rglob('*.(jpe?g|png)'))
print(len(FILE_PATHS))
FILE_PATHS=list(Path('./photos/test').rglob('*.jpg'))#11104
print(len(FILE_PATHS))
0
11104
Run Code Online (Sandbox Code Playgroud) pathlib ×10
python ×10
glob ×2
python-3.x ×2
directory ×1
django ×1
pandas ×1
path ×1
subdirectory ×1