百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python文件操作pathlib(python文件操作步骤)

off999 2024-09-20 22:40 55 浏览 0 评论

pathlib 文件操作模块

阅读需要 15分钟。

  • 之使用 python 操作文件路径,最苦开始使用 os.path。
  • pathlib 库从 python3.4 开始,到 python3.6 已经比较成熟。

为什么会有pathlib模块:规范统一

  1. 老的路径操作函数比较混乱, os, os.path 当中,现在统一可以用 pathlib 管理。
  2. 老的API对于不同操作系统的处理 win,mac 以及 linux 不方便
  3. 老方法使用的是函数,返回的路径通常是个”字符串“,但是字符串还是路径
  4. pathlib 使用简单功能丰富。

pathlib使用 import mathlob 或者 from pathlib import Path

from pathlib import Path

当前目录在哪里

from pathlib import Path
pwd = Path.cwd()
print(pwd)

home目录

from pathlib import Path
pwd = Path.cwd()

print(pwd)
print(Path.home())
C:\Users\admin


home目录在Windows上通常是 c:/User/用户名 这个目录,而Linux通常也是用户的主目录

下面是一个linux服务器上root用户的home目录 /root


Paht的各种用法

  • 根据字符串构建目录: Path(r"C:\Users\philipp\realpython\file.txt")
p =Path(r"C:\Users\philipp\realpython\file.txt")
print(p,)
print(p.parent) # 获取上级目录
C:\Users\philipp\realpython\file.txt
C:\Users\philipp\realpython

Path对象的parent方法可以找到它的上层目录,一直可以找到最上层的根目录

  • 获取当前执行的Python文件的完整路径和目录
print(Path(__file__))
print(Path(__file__).parent)
  • 移动文件:比如将某个目录下的 txt文本文件移到到其他目录
for file_path in Path.cwd().glob("*.txt"):
    # new_path = Path("archive",file_path.name)    
    new_path = Path("archive") / file_path.name
    #以上两种方式都是构建新目录文件 的路径,效果是一样的
    print(new_path)
    file_path.rename(new_path)
  • 组合文件路径 joinpath
a  = Path.home().joinpath("python", "scripts", "test.py")
print(a)


Paht对象的关键组件

  • .name: 文件名,没有目录路径 a.txt
  • .stem: 没有扩展名的文件名 a
  • .suffix: 文件后缀
  • .anchor: 文件作者
  • .parent: 父目录
>>> from pathlib import Path
>>> path = Path(r"C:\Users\gahjelle\realpython\test.md")
>>> path
WindowsPath('C:/Users/gahjelle/realpython/test.md')

>>> path.name
'test.md'

>>> path.stem
'test'

>>> path.suffix
'.md'

>>> path.anchor
'C:\\'

>>> path.parent
WindowsPath('C:/Users/gahjelle/realpython")

>>> path.parent.parent
WindowsPath('C:/Users/gahjelle')

使用 / 斜杠 连接目录如下

path.parent.parent / f"new{path.suffix}"
PosixPath('/home/gahjelle/new.md')

读取文件

假设有一个文件 的内容如下

<!-- shopping_list.md -->

# Shopping List

## Fruit

* Banana
* Apple
* Peach

## Candy

* Chocolate
* Nougat Bits



# read_shopping_list.py

from pathlib import Path

path = Path.cwd() / "shopping_list.md"
with path.open(mode="r", encoding="utf-8") as md_file:
    content = md_file.read()
    groceries = [line for line in content.splitlines() if line.startswith("*")]
print("\n".join(groceries))
  • .read_text() 字符串方式读取文件
  • .read_bytes() 二进制方式读取文件
  • .write_text() 写入文本到 文件
  • .write_bytes() 写入二进制数据到 文件
from pathlib import Path

path = Path.cwd() / "shopping_list.md"
content = path.read_text(encoding="utf-8")
groceries = [line for line in content.splitlines() if line.startswith("*")]
print("\n".join(groceries))

#写文件
Path("plain_list.md").write_text("\n".join(groceries), encoding="utf-8")

重命名文件

>>> from pathlib import Path
>>> txt_path = Path("/home/gahjelle/realpython/hello.txt")
>>> txt_path
PosixPath("/home/gahjelle/realpython/hello.txt")

>>> md_path = txt_path.with_suffix(".md")
PosixPath('/home/gahjelle/realpython/hello.md')

>>> txt_path.replace(md_path)

with_suffix 构建一个新的Paht 把 .txt 后缀修改为 .md

使用 replace函数把电脑上的文件名重新命名

复制文件:其中一种办法 内容复制创建新文件

>>> source = Path("shopping_list.md")
>>> destination = source.with_stem("shopping_list_02")
>>> destination.write_bytes(source.read_bytes())

创建新文件 touch 函数

>>> from pathlib import Path
>>> filename = Path("hello.txt")
>>> filename.exists()
False

>>> filename.touch()
>>> filename.exists()
True

>>> filename.touch()

如果文件已经存在,调用touch函数时exist_ok为False则会报错。

>>> filename.touch(exist_ok=False)
Traceback (most recent call last):
  ...
FileExistsError: [Errno 17] File exists: 'hello.txt'

Pathlib应用小例子

统计不同文件类型的数量

>>> from pathlib import Path
>>> from collections import Counter
>>> Counter(path.suffix for path in Path.cwd().iterdir())
Counter({'.md': 2, '.txt': 4, '.pdf': 2, '.py': 1})
>>> from collections import Counter
>>> Counter(path.suffix for path in Path.cwd().iterdir())
Counter({'': 8, '.dll': 4, '.txt': 2, '.exe': 2})
>>> 

显示目录的树形结构

def tree(directory):
    print(f"+ {directory}")
    for path in sorted(directory.rglob("*")):
        depth = len(path.relative_to(directory).parts)
        spacer = "    " * depth
        print(f"{spacer}+ {path.name}")



查找最近修改的文件

>> from pathlib import Path
>>> from datetime import datetime
>>> directory = Path.cwd()
>>> time, file_path = max((f.stat().st_mtime, f) for f in directory.iterdir())
>>> print(datetime.fromtimestamp(time), file_path)
2022-04-03 09:30:57.448853 C:\Users\admin\AppData\Local\Programs\Python\Python38\Scripts
>>> 

创建唯一的文件名,不重名

def unique_path(directory, name_pattern):
    counter = 0
    while True:
        counter += 1
        path = directory / name_pattern.format(counter)
        if not path.exists():
            return path

代码很简单实际上就是有一个计数器 counter作为文件名中的一部分如果存在同名的文件,counter 加1 直到没有重复的名字。

相关推荐

安全教育登录入口平台(安全教育登录入口平台官网)

122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...

大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)

大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...

谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)

要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...

2026-02-04 09:03 off999

电信宽带测速官网入口(电信宽带测速官网入口app)

这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...

植物大战僵尸95版手机下载(植物大战僵尸95 版下载)

1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...

免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)

1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...

2025世界杯赛程表(2025世界杯在哪个国家)

2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...

下载搜狐视频电视剧(搜狐电视剧下载安装)

搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...

pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
永久免费听歌网站(丫丫音乐网)

可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...

音乐格式转换mp3软件(音乐格式转换器免费版)

有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...

电子书txt下载(免费的最全的小说阅读器)

1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...

最好免费观看高清电影(播放免费的最好看的电影)

在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...

孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)

要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...

取消回复欢迎 发表评论: