今天被安利了pathlib庫,感受就是為什麼我直到今天才發現這個東西。。。。。
Path子產品
先來個執行個體看看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
<WindowsPath.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