1. 程式人生 > 程式設計 >python中pathlib模組的基本用法與總結

python中pathlib模組的基本用法與總結

前言

相比常用的 os.path而言,pathlib 對於目錄路徑的操作更簡介也更貼近 Pythonic。但是它不單純是為了簡化操作,還有更大的用途。

pathlib 是Python內建庫,Python 文件給它的定義是:The pathlib module – object-oriented filesystem paths(面向物件的檔案系統路徑)。pathlib 提供表示檔案系統路徑的類,其語義適用於不同的作業系統。

python中pathlib模組的基本用法與總結

更多詳細的內容可以參考官方文件:https://docs.python.org/3/library/pathlib.html#methods

1. pathlib模組下Path類的基本使用

from pathlib import Path

path = r'D:\python\pycharm2020\program\pathlib模組的基本使用.py'
p = Path(path)
print(p.name)  # 獲取檔名
print(p.stem)  # 獲取檔名除字尾的部分
print(p.suffix)  # 獲取檔案字尾
print(p.parent)  # 相當於dirname
print(p.parent.parent.parent)
print(p.parents) # 返回一個iterable 包含所有父目錄
for i in p.parents:
 print(i)
print(p.parts)  # 將路徑通過分隔符分割成一個元組

執行結果如下:

pathlib模組的基本使用.py
pathlib模組的基本使用
.py
D:\python\pycharm2020\program
D:\python
<WindowsPath.parents>
D:\python\pycharm2020\program
D:\python\pycharm2020
D:\python
D:\
('D:\\','python','pycharm2020','program','pathlib模組的基本使用.py')

  • Path.cwd():Return a new path object representing the current directory
  • Path.home():Return a new path object representing the user's home directory
  • Path.expanduser():Return a new path with expanded ~ and ~user constructs
from pathlib import Path

path_1 = Path.cwd()  # 獲取當前檔案路徑
path_2 = Path.home()
p1 = Path('~/pathlib模組的基本使用.py')
print(path_1)
print(path_2)
print(p1.expanduser())

執行結果如下:

D:\python\pycharm2020\program
C:\Users\Administrator
C:\Users\Administrator\pathlib模組的基本使用.py

Path.stat():Return a os.stat_result object containing information about this path

from pathlib import Path
import datetime

p = Path('pathlib模組的基本使用.py')
print(p.stat())   # 獲取檔案詳細資訊
print(p.stat().st_size) # 檔案的位元組大小
print(p.stat().st_ctime) # 檔案建立時間
print(p.stat().st_mtime) # 上次修改檔案的時間
creat_time = datetime.datetime.fromtimestamp(p.stat().st_ctime)
st_mtime = datetime.datetime.fromtimestamp(p.stat().st_mtime)
print(f'該檔案建立時間:{creat_time}')
print(f'上次修改該檔案的時間:{st_mtime}')

執行結果如下:

os.stat_result(st_mode=33206,st_ino=3659174698076635,st_dev=3730828260,st_nlink=1,st_uid=0,st_gid=0,st_size=543,st_atime=1597366826,st_mtime=1597366826,st_ctime=1597320585)
543
1597320585.7657475
1597366826.9711637
該檔案建立時間:2020-08-13 20:09:45.765748
上次修改該檔案的時間:2020-08-14 09:00:26.971164

從不同.stat().st_屬性 返回的時間戳表示自1970年1月1日以來的秒數,可以用datetime.fromtimestamp將時間戳轉換為有用的時間格式。

Path.exists():Whether the path points to an existing file or directory
Path.resolve(strict=False):Make the path absolute,resolving any symlinks. A new path object is returned

from pathlib import Path

p1 = Path('pathlib模組的基本使用.py')   # 檔案
p2 = Path(r'D:\python\pycharm2020\program') # 資料夾 
absolute_path = p1.resolve()
print(absolute_path)
print(Path('.').exists())
print(p1.exists(),p2.exists())
print(p1.is_file(),p2.is_file())
print(p1.is_dir(),p2.is_dir())
print(Path('/python').exists())
print(Path('non_existent_file').exists())

執行結果如下:

D:\python\pycharm2020\program\pathlib模組的基本使用.py
True
True True
True False
False True
True
False

Path.iterdir():When the path points to a directory,yield path objects of the directory contents

from pathlib import Path

p = Path('/python')
for child in p.iterdir():
  print(child)

執行結果如下:

\python\Anaconda
\python\EVCapture
\python\Evernote_6.21.3.2048.exe
\python\Notepad++
\python\pycharm-community-2020.1.3.exe
\python\pycharm2020
\python\pyecharts-assets-master
\python\pyecharts-gallery-master
\python\Sublime text 3

Path.glob(pattern):Glob the given relative pattern in the directory represented by this path,yielding all matching files (of any kind),The “**” pattern means “this directory and all subdirectories,recursively”. In other words,it enables recursive globbing.

Note:Using the “**” pattern in large directory trees may consume an inordinate amount of time

遞迴遍歷該目錄下所有檔案,獲取所有符合pattern的檔案,返回一個generator。

獲取該檔案目錄下所有.py檔案

from pathlib import Path

path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.py')
print(type(file_name))  # <class 'generator'>
for i in file_name:
  print(i)

獲取該檔案目錄下所有.jpg圖片

from pathlib import Path

path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.jpg')
print(type(file_name))  # <class 'generator'>
for i in file_name:
  print(i)

獲取給定目錄下所有.txt檔案、.jpg圖片和.py檔案

from pathlib import Path

def get_files(patterns,path):
  all_files = []
  p = Path(path)
  for item in patterns:
    file_name = p.rglob(f'**/*{item}')
    all_files.extend(file_name)
  return all_files

path = input('>>>請輸入檔案路徑:')
results = get_files(['.txt','.jpg','.py'],path)
print(results)
for file in results:
  print(file)

Path.mkdir(mode=0o777,parents=False,exist_ok=False)

  • Create a new directory at this given path. If mode is given,it is combined with the process' umask value to determine the file mode and access flags. If the path already exists,FileExistsError is raised.
  • If parents is true,any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
  • If parents is false (the default),a missing parent raises FileNotFoundError.
  • If exist_ok is false (the default),FileExistsError is raised if the target directory already exists.
  • If exist_ok is true,FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command),but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

Path.rmdir():Remove this directory. The directory must be empty.

from pathlib import Path

p = Path(r'D:\python\pycharm2020\program\test')
p.mkdir()
p.rmdir()
from pathlib import Path

p = Path(r'D:\python\test1\test2\test3')
p.mkdir(parents=True) # If parents is true,any missing parents of this path are created as needed
p.rmdir()  # 刪除的是test3資料夾
from pathlib import Path

p = Path(r'D:\python\test1\test2\test3')
p.mkdir(exist_ok=True)
  • Path.unlink(missing_ok=False):Remove this file or symbolic link. If the path points to a directory,use Path.rmdir() instead. If missing_ok is false (the default),FileNotFoundError is raised if the path does not exist. If missing_ok is true,FileNotFoundError exceptions will be ignored. Changed in version 3.8:The missing_ok parameter was added.
  • Path.rename(target):Rename this file or directory to the given target,and return a new Path instance pointing to target. On Unix,if target exists and is a file,it will be replaced silently if the user has permission. target can be either a string or another path object.
  • Path.open(mode=‘r',buffering=-1,encoding=None,errors=None,newline=None):Open the file pointed to by the path,like the built-in open() function does.
from pathlib import Path

p = Path('foo.txt')
p.open(mode='w').write('some text')
target = Path('new_foo.txt')
p.rename(target)
content = target.open(mode='r').read()
print(content)
target.unlink()

2. 與os模組用法的對比

python中pathlib模組的基本用法與總結

總結

到此這篇關於python中pathlib模組的基本用法與總結的文章就介紹到這了,更多相關python pathlib模組用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!