Python / pathlib === ###### tags: `Python` ###### tags: `Python`, `os`, `pathlib`, `name`, `stem`, `suffix`, `exists`, `getsize` <br> [TOC] <br> - ### file path ```python # 絕對路徑 Path(filepath).resolve() ``` - [How to get absolute path of a pathlib.Path object?](https://stackoverflow.com/questions/42513056/) - ### file name ```python Path(filepath).name ``` - ### file size ```python os.path.getsize(pmc_tar_file) ``` ``` Path(filepath).stat().st_size ``` - `.stat()` - os.stat_result (範例) - st_mode=33188 - st_ino=143939787 - st_dev=2051 - st_nlink=1 - st_uid=0 - st_gid=0 - st_size=19968 - st_atime=1744339126 - st_mtime=1744339126 - st_ctime=1744339126 - ### file extension ```python Path(filepath).suffix ``` - ### file exist ```python Path(filepath).exists(): ``` - ### list folder - 列出當前目錄下的子目錄 ```python= from pathlib import Path # 取得目前目錄的 Path 物件 current_dir = Path('.') for item in current_dir.iterdir(): if item.is_dir(): print(item) ``` - ### list file - 列出當前目錄下的檔案 ```python= from pathlib import Path # 取得目前目錄的 Path 物件 current_dir = Path('.') for item in current_dir.iterdir(): if item.is_file(): print(item) ``` - [Listing of all files in directory?](https://stackoverflow.com/questions/39909655) ```python p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*') files = [x for x in p if x.is_file()] ``` - Q&A - Question `Path.glob('**/*')` 用法為何 - ChatGPT4 `Path.glob('**/*')` 是 `pathlib` 模組中的一種方式,用於尋找匹配特定模式的檔案路徑。在這個表達式中,`**` 代表任意多層的目錄,`*` 代表任意長度的檔案名(包括檔案和目錄)。因此,`Path.glob('**/*')` 會遞迴地列舉出從當前目錄下所有檔案和子目錄中的所有項目。 這裡有個具體的範例來說明如何使用它: ```python= from pathlib import Path # 設置起始目錄,'.' 代表當前目錄 base_path = Path('.') # 使用 glob 模式 '**/*' 遍歷所有檔案和目錄 for path in base_path.glob('**/*'): print(path) ``` 這段程式碼將從程式執行的當前目錄開始,列印出所有子目錄及其內部的檔案和目錄的路徑。這種方法非常適合於需要處理目錄樹中的檔案時使用,例如搜尋特定類型的檔案或執行批量操作。 `glob` 方法返回一個生成器,因此它不會立即載入所有的路徑,而是按需生成每一個路徑。這樣做可以提高效率,尤其是在處理非常大的檔案系統時。 - ### is: is_symlink - ### mkdir > [doc](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir) > `mkdir(parents=True, exist_ok=True)` - ### path 串接 - ### Case1:同目錄下某個檔案 - 作法1 ```python file_path = Path('a/b/text.txt') Path(file_path.parent, 'README.md') # PosixPath('a/b/README.md') ``` - 作法2 ```python file_path = Path('a/b/text.txt') file_path.parent / 'README.md' # PosixPath('a/b/README.md') ``` - 作法3 (較佳作法) ```python file_path = Path('a/b/text.txt') file_path.with_name('README.md') # PosixPath('a/b/README.md') ``` - ### Case2:檔名串接 - 'a/b/text.tar' -> 'a/b/text.tar.gz' ```python file_path = Path('a/b/text.tar') file_path.with_name(file_path.name + '.gz') # PosixPath('a/b/text.tar.gz') ``` - ### Case3:副檔名置換 - 'a/b/text.txt' -> 'a/b/text.zip' ```python file_path = Path('a/b/text.tar') file_path.with_suffix('.zip') # PosixPath('a/b/text.zip') ``` - `with_suffix('zip')` 中的 `zip` 少了 ".",會引發錯誤: ValueError: Invalid suffix 'zip' ![](https://hackmd.io/_uploads/ByIPTZUA1x.png) - ### path 比較 ```python= from pathlib import Path def are_paths_same(path1, path2): p1 = Path(path1).resolve() p2 = Path(path2).resolve() return p1 == p2 # 測試範例 path1 = "/some/path/to/directory" path2 = "/some/path/to/directory/." print(are_paths_same(path1, path2)) # 這將輸出 True 如果兩個路徑相同 ``` <br> ## 教學 - [(python)使用pathlib替代os.path(轉錄)](https://medium.com/ai%E5%8F%8D%E6%96%97%E5%9F%8E/edc9defb2bd8) - [Introduction to the Python Pathlib Module](https://stackabuse.com/introduction-to-the-python-pathlib-module/) <br> {%hackmd vaaMgNRPS4KGJDSFG0ZE0w %}