发现了遍历文件夹下文件更简单的方法库了,激动。

你就看看代码相比os模块有多简单:

root = Path("./try—_python")
new_dir = root/Path("test")  # 这句话相当于 new_dir = os.path.join(root, 'test')
print(str(new_dir))

 


from pathlib import Path

#
找到这个路径下的txt文件夹 path = Path(r"./txt") # 遍历txt文件夹下的所有txt文件,挨个打开,写入内容“abc” for p in path.rglob("*.txt"): with open(p, "a", encoding="utf-8") as f: f.write("abc")

 

文件匹配相关操作:

Path.iterdir()  # 遍历目录的子目录或者文件

Path.is_dir()  # 判断是否是目录

Path.glob()  # 过滤目录(返回生成器)

Path.resolve()  # 返回绝对路径

Path.exists()  # 判断路径是否存在

Path.open()  # 打开文件(支持with)

Path.unlink()  # 删除文件或目录(目录非空触发异常)

Path.chmod()  # 更改路径权限, 类似os.chmod()

Path.expanduser()  # 展开并返回完整路径对象

Path.mkdir()  # 创建目录

Path.rename()  # 重命名路径

Path.rglob()  # 递归遍历所有子目录的文件

Path.parts  # 分割路径 类似os.path.split(), 不过返回元组

path.suffix    # 文件后缀

path.stem      # 文件名不带后缀

path.name      # 带后缀的完整文件名

path.parent    # 路径的上级目录

 

 

 

参考:https://www.jianshu.com/p/84f31a23aca7

posted on 2019-12-08 22:25  天马行宇  阅读(357)  评论(0编辑  收藏  举报