今天被安利了pathlib库,感受就是为什么我直到今天才发现这个东西。。。。。
先来个实例看看pathlib有多好用,如果一个目录中有很多文件,但他们的后缀名并不统一,既有.txt, 又有.csv。我们需要将其中的.txt结尾的文件全部修改成.csv后缀。
可以这么实现:
'''
将txt结尾的文件重命名为.csv文件
'''
import os
def rename_files(path):
for files in os.listdir(path):
filename, ext = os.path.splitext(files)
if ext == '.txt':
source_file = os.path.join(path,files)
os.rename(source_file, os.path.join(path, f'{filename}.csv'))
上面的代码一共用了:
os.listdir(path)、os.path.splitext(files),os.path.join(path,files),os.rename()好几个模块
如果是用pathlib处理的话:
from pathlib import Path
def rename_files(path):
for fpath in Path(path).glob('*.txt'):
fpath.rename(fpath.with_suffix('.csv'))
首先使用 Path(path) 将字符串路径转换为 Path 对象
调用 .glob(’*.txt’) 对路径下所有内容进行模式匹配并以生成器方式返回,结果仍然是 Path 对象,所以我们可以接着做后面的操作
使用 .with_suffix(’.csv’) 直接获取使用新后缀名的文件全路径
调用 .rename(target) 完成重命名
相比 os 和 os.path,引入 pathlib 模块后的代码明显更精简,也更有整体统一感。所有文件相关的操作都是一站式完成。
常用操作:
>>>from pathlib import Path
#创建Path对象
>>> p = Path('E:\\test\\test.py')
>>> p
WindowsPath('E:/test/test.py')
#获取文件名
>>> p.name
'test.py'
#获取文件名除后缀的部分
>>> p.stem
'test'
#获取文件名后缀
>>> p.suffix
'.py'
#相当于dirname
>>> p.parent
WindowsPath('E:/test')
#返回一个iterable,包含所有的父目录
>>> p.parents
>>> for i in p.parents:
... print(i)
...
E:\test
E:\
#将路径通过分隔符分割成一个元组
>>> p.parts
('E:\\', 'test', 'test.py')
#组合文件路径,相当于os.path.join()
>>>p1 = Path('E:/test/')
>>>p2 = p1/ '123'
>>>p2
WindowsPath('E:/test/123')
#获取当前路径,相当于os.getcwd()
>>>pwd = Path.cwd()
#判断当路径是否存在
>>> Path('.').exists()
True
>>> Path('move.py').exists()
True
>>> Path('hello.py').exists()
False
#获取路径下所有符合的文件
>>>files = Path.glob('*.txt') #例子,返回后缀是txt的文件,返回结果是一个generator
>>>for file in files:
print(file)
Path.rglob(pattern):与上面类似,只不过是返回路径中所有子文件夹的符合pattern的文件。
Path.is_dir() : 判断该路径是否是文件夹
Path.is_file(): 判断该路径是否是文件
#遍历文件夹下的文件
>>>p = Path.cwd()
>>>for i in p.iterdir();
print(i)
#重命名当前文件或文件夹,如果target所指示的文件或文件夹已存在,则覆盖原文件
>>>Path.replace(target)
# Path.match(pattern)
判断path是否满足pattern
# Path.rmdir()
当path为空文件夹的时候,删除该文件夹
移动和删除文件
使用replace可以移动文件,但如果文件存在,则会覆盖。为避免覆盖,在替换之前最好测试目标文件是否存在
from pathlib import Path
pwd = Path.cwd()
des = pwd / 'target'
sou = pwd / 'demo.txt'
if not des.exists():
sou.replace(des)
上面这种方法只适用于单个文件的操作,多文件操作时采用下面这种方式:
from pathlib import Path
pwd = Path.cwd()
des = pwd / 'target'
sou = pwd / 'demo.txt'
with des.open('rb') as file:
file.write(sou.read_bytes())
但,当des文件存在时,上述代码会出现FileExistsError异常。
从技术上讲,这会复制一个文件。要执行移动,只需要在复制完成后删除源文件即可。
使用with_name 和 with.shuffix可以修改文件名字或者后缀
from pathlib import Path
pwd = Path.cwd()
sou = pwd / 'demo.py'
sou.replace(sou.with_suffix('.txt')) #修改后缀并移动文件,即重命名
可以使用.rmdir()和.unlink()来删除文件
from pathlib import Path
pwd = Path.cwd()
des = pwd / 'target'
sou = pwd / 'demo.txt'
sou.unlink()
参考文章:https://zhuanlan.zhihu.com/p/69723040
https://blog.csdn.net/amanfromearth/article/details/80265843
https://zhuanlan.zhihu.com/p/68197380