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

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

off999 2024-09-20 22:40 26 浏览 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 直到没有重复的名字。

相关推荐

第九章:Python文件操作与输入输出

9.1文件的基本操作9.1.1打开文件理论知识:在Python中,使用open()函数来打开文件。open()函数接受两个主要参数:文件名和打开模式。打开模式决定了文件如何被使用,常见的模式有:&...

Python的文件处理

一、文件处理的流程1.打开文件,得到文件句柄并赋值给一个变量2.通过句柄对文件进行操作3.关闭文件示例:d=open('abc')data1=d.read()pri...

Python处理文本的25个经典操作

Python处理文本的优势主要体现在其简洁性、功能强大和灵活性。具体来说,Python提供了丰富的库和工具,使得对文件的读写、处理变得轻而易举。简洁的文件操作接口Python通过内置的open()函数...

Python学不会来打我(84)python复制文件操作总结

上一篇文章我们分享了python读写文件的操作,主要用到了open()、read()、write()等方法。这一次是在文件读写的基础之上,我们分享文件的复制。#python##python自学##...

python 文件操作

1.检查目录/文件使用exists()方法来检查是否存在特定路径。如果存在,返回True;如果不存在,则返回False。此功能在os和pathlib模块中均可用,各自的用法如下。#os模块中e...

《文件操作(读写文件)》

一、文件操作基础1.open()函数核心语法file=open("filename.txt",mode="r",encoding="utf-8"...

栋察宇宙(二十一):Python 文件操作全解析

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“Python文件操作全解析”欢迎您的访问!Sharethefun,spreadthe...

值得学习练手的70个Python项目(附代码),太实用了

Python丰富的开发生态是它的一大优势,各种第三方库、框架和代码,都是前人造好的“轮子”,能够完成很多操作,让你的开发事半功倍。下面就给大家介绍70个通过Python构建的项目,以此来学习Pytho...

python图形化编程:猜数字的游戏

importrandomnum=random.randint(1,500)running=Truetimes=0##总的次数fromtkinterimport*##导入所有tki...

一文讲清Python Flask的Web编程知识

刚入坑Python做Web开发的新手,还在被配置臃肿、启动繁琐折磨?Flask这轻量级框架最近又火出圈,凭5行代码启动Web服务的极致简洁,让90后程序员小张直呼真香——毕竟他刚用这招把部署时间从半小...

用python 编写一个hello,world

第一种:交互式运行一个hello,world程序:这是写python的第一步,也是学习各类语言的第一步,就是用这种语言写一个hello,world程序.第一步,打开命令行窗口,输入python,第二步...

python编程:如何使用python代码绘制出哪些常见的机器学习图像?

专栏推荐绘图的变量单变量查看单变量最方便的无疑是displot()函数,默认绘制一个直方图,并你核密度估计(KDE)sns.set(color_codes=True)np.random.seed(su...

如何编写快速且更惯用的 Python 代码

Python因其可读性而受到称赞。这使它成为一种很好的第一语言,也是脚本和原型设计的流行选择。在这篇文章中,我们将研究一些可以使您的Python代码更具可读性和惯用性的技术。我不仅仅是pyt...

Python函数式编程的详细分析(代码示例)

本篇文章给大家带来的内容是关于Python函数式编程的详细分析(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。FunctionalProgramming,函数式编程。Py...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(七)

适合Python3+的6道编程练习题(附详解)1.检查字符串是否以指定子串开头题目描述:判断字符串是否以给定子串开头(如"helloworld"以"hello&...

取消回复欢迎 发表评论: