程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python] pathlib uses

編輯:Python

pathlib

  • Python built-in, version >= 3.4
  • in consideration of Windows/Linux And other path differences under different operating systems , It is not recommended to use os.path.* And string to manage the path .
  • from pathlib import Path
operation Example remarks establish p = Path('C:/Users/Username/Documents) It could be a file , It could be a folder , There is no guarantee that there is something in this path p = Path('C: \\', 'Users', 'Username', 'Documents') Equivalent writing , You can take each part apart p2 = p.with_name('file2.txt') Get other files in the same folder quickly Path object p2 = p.with_suffix('.csv') Get the same file quickly basename But with different suffixes Path object Splicing p = Path(...) / str_of_subpath It's very natural to connect with a division sign p = Path(...).joinpath(str_of_subpath) You can also use the method Full path string str(p) Get the next level p.parent Folder's parent folder ; The folder where the file is located ; You can use multiple parent obtain basename, noext-basename, extp.name, p.stem, p.suffix Get the folder (os.path.dirname)p.parent that will do . If you still need to get the path of the folder str() Get the character string Tuples p.partsWindows Of C: \\ Is a separate string Whether there is , Is it a document / Folder p.exists(), p.is_file(), p.is_dir() Traverse p.iterdir() Return to generator , You can use for iteration , You need to judge whether it is a folder lookup ( Based on regularization )p.glob('*.txt') Return to generator , You need to judge whether it is a folder , see 4 glob built-inp.glob('*/*.txt') Find the current folder at the next lower level In all folders txtp.glob('**/*.txt') Find the current folder Lower all levels In a folder txt Reading and writing p.read_text(...), p.read_bytes(...)
p.write_text(...), p.write_bytes(...) You don't have to call open Open the withwith p.open('r') as f: And ordinary open Same use Determine whether the two paths are equivalent p.samefile(str_of_file) establish / Delete empty Folder p.mkdir(), p.rmdir()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved