- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
有没有办法删除 PathLib 模块中的目录及其内容?使用 path.unlink()
它只删除一个文件,使用 path.rmdir()
目录必须是空的。有没有办法在一个函数调用中做到这一点?
最佳答案
如您所知,仅有的两个用于删除文件/目录的 Path
方法是 .unlink()
和 .rmdir()
和你想要的也没有。
Pathlib 是一个提供跨不同操作系统的面向对象路径的模块,它并不意味着有很多不同的方法。
The aim of this library is to provide a simple hierarchy of classes tohandle filesystem paths and the common operations users do over them.
“不常见”的文件系统更改,例如递归删除目录,存储在不同的模块中。如果你想递归地删除一个目录,你应该使用 shutil
模块。 (它也适用于 Path
实例!)
import shutil
import pathlib
import os # for checking results
print(os.listdir())
# ["a_directory", "foo.py", ...]
path = pathlib.Path("a_directory")
shutil.rmtree(path)
print(os.listdir())
# ["foo.py", ...]
关于python - PathLib 递归删除目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186904/
这是我第一次在这个网站上提问,如果我的问题没有正确布置,请见谅 y@DESKTOP-MQJ3NCT:~/Real-Time-Voice-Cloning$ python demo_toolbox.py
所以我刚刚将 matplotlib 更新到版本 3.0.2 。我可以很好地导入 matplotlib,但是当我尝试 import matplotlib.pyplot 时,我得到: ----------
考虑以下路径: import pathlib path = pathlib.Path(r'C:\users\user1\documents\importantdocuments') 如何从 Path
如果我想指定一个路径来保存文件并创建该路径中不存在的目录,是否可以在一行代码中使用 pathlib 库来完成此操作? 最佳答案 是的,就是Path.mkdir : pathlib.Path('/tmp
有没有办法删除 PathLib 模块中的目录及其内容?使用 path.unlink() 它只删除一个文件,使用 path.rmdir() 目录必须是空的。有没有办法在一个函数调用中做到这一点? 最佳答
我主要使用 pathlib 而不是 os 作为路径,但是有一件事我没能在 pathlib 上工作。例如,如果我需要目录中最新创建的 .csv,我会使用 glob & os import glob im
我正在尝试使用 %userprofile%\desktop 之类的 win 环境变量和 pathlib 来保护不同用户 PC 中的文件。 但我无法让它工作,它一直保存在正在运行的脚本目录中。 impo
给定两个 Python Pathlib 路径,其中一个是另一个(未知深度)的后缀, x = Path("/a/b/c/d/e.ext") y = Path("d/e.ext") 是否有一种“不错”的方
在python3中,对未知(用户输入)文件路径进行操作时,需要支持./r*/*.dat等通配符。计划是使用这样的东西(简化): paths = [] for test in userinputs:
如何从使用 parts 构造的元组获取在 pathlib回到实际的字符串路径? from pathlib import Path p = Path(path) parts_tuple = p.p
python3系列最近添加了一个名为pathlib的面向对象的路径操作库。我希望能够断言子文件是父文件的后代,以避免人们阅读/etc/passwd 等。标准库不提供有关安全使用 pathlib 的任何
我已经使用 setup.py 打包了我的项目,项目文件夹结构如下所示。 api-automation api packagename __init__.py
我正在使用库pathlib,并尝试通过以下方式构建路径。 BASE_DIR = Path(__file__).ancestor(3) secrets_file = BASE_DIR / 'main_a
我开始使用pathlib,并且在很大程度上非常喜欢使用它。我遇到的问题是由于方法而不是函数的性质而对其进行测试。 def test_correct_dir_was_made(self): wi
我想使用相对路径和子进程模块,以便能够运行不同的可执行文件。 为了获取相对路径,在阅读不同的线程之后,我认为 pathlib 模块是最好的选择。 假设我的 python 脚本位于 Windows 的特
我正在创建一个根据类而不同的格式字符串,用于通过通用类方法生成文件名。我使用 Python 3.4+ pathlib.Path 模块进行面向对象的文件 I/O。 在构建此字符串时,缺少路径分隔符,我想
我想用一个额外的构造函数断言子类型pathlib.Path,如下所示 import pathlib class TempDirPath(type(pathlib.Path())): def _
我正在尝试在 Python 中使用相对路径,并且我想将我的 csv 文件与我的 python 代码放在一个单独的文件夹中。 我的 python 程序在以下文件夹中: G:\projects\code
我正在尝试使用 Python 的 pathlib 模块测试程序。使用 os 模块,您过去只需遵循相同的类似 url 的形式即可访问网络驱动器。但出于某种原因,您不能使用 pathlib 执行此操作。或
我的目录结构可能类似于 Data Current A B C Previous A X 在尽可能简单/快
我是一名优秀的程序员,十分优秀!