{"id":21351883,"url":"https://github.com/hygull/try-pathlib","last_synced_at":"2025-03-16T04:41:31.199Z","repository":{"id":80469013,"uuid":"173151188","full_name":"hygull/try-pathlib","owner":"hygull","description":"A repository containing basic usage examples of Python's pathlib library with beautiful documentation. Visit and check beautiful documentation at","archived":false,"fork":false,"pushed_at":"2019-03-04T08:27:50.000Z","size":5684,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-22T17:13:41.991Z","etag":null,"topics":["os","pathlib","python34"],"latest_commit_sha":null,"homepage":"https://hygull.github.io/try-pathlib/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hygull.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-28T16:54:50.000Z","updated_at":"2019-03-04T08:27:52.000Z","dependencies_parsed_at":null,"dependency_job_id":"305941b6-8452-4a04-8d5d-9c33afa51145","html_url":"https://github.com/hygull/try-pathlib","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hygull%2Ftry-pathlib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hygull%2Ftry-pathlib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hygull%2Ftry-pathlib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hygull%2Ftry-pathlib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hygull","download_url":"https://codeload.github.com/hygull/try-pathlib/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243826789,"owners_count":20354220,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["os","pathlib","python34"],"created_at":"2024-11-22T03:11:43.117Z","updated_at":"2025-03-16T04:41:31.178Z","avatar_url":"https://github.com/hygull.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Python's pathlib - usage examples\n\nThis documenation presents basic usage examples of Python's **pathlib** library. Before trying examples in this page make sure to check your Python version by reading the below note or [visit here](https://pypi.org/project/pathlib/?fbclid=IwAR0-Jk14-IkTLCNldiHXvv5HAzhE_C71YDMdv9vmfT0QtlILYZku_7gLKSM) to check.\n\n\n![Pathlib-inheritance](./images/pathlib-inheritance.png)\n\n## What it offers, what speciality it has?\n\n**pathlib** offers a set of classes to handle filesystem paths. It offers the following advantages over using string objects:\n\n+ No more cumbersome use of os and os.path functions. Everything can be done easily through operators, attribute accesses, and method calls.\n\n+ Embodies the semantics of different path types. For example, comparing Windows paths ignores casing.\n\n+ Well-defined semantics, eliminating any warts or ambiguities (forward vs. backward slashes, etc.).\n\n| pathlib | inheritance |\n| --- | --- |\n| ![pathlib](./images/pathlib-2nd.png)|![inheritance](./images/7tVD0.png)|\n\n## Note\n\n+ Python **3.2** or later is recommended, but pathlib is also usable with Python **2.7** and **2.6**.\n\n+ From Python **3.4**, pathlib is now part of the standard library. For Python **3.3** and earlier, `easy_install pathlib` or `pip install pathlib` should do the trick.\n\n\n\u0026raquo; Mean to say\n\n| Python 2.6 - Python3.3 | \u003e= Python 3.4 |\n| --- | --- |\n| `pip install pathlib` OR | No installation is required just try it |\n| `easy_install pathlib` | Now it's the part of Python's standard library |\n\n\u003e Mine is Python **3.7.2** and I am trying it on **MAC OS Mojave**.\n\n![pathlib](./images/python3-pathlib-title.webp)\n\n## Directory structure of working directory\n\nWe will be working on [root](./root) directory. This directory has the following structure.\n\n```bash\nRishikeshs-MacBook-Air:try-pathlib hygull$ pwd\n/Users/hygull/Projects/Python3/try-pathlib\nRishikeshs-MacBook-Air:try-pathlib hygull$ tree root/\n\n```\n\n```bash\nroot/\n├── c\n│   └── examples\n│       ├── c-main.md\n│       └── hello.c\n├── cpp\n│   ├── docs\n│   │   └── notes.md\n│   └── hello.cpp\n├── doc.md\n├── go\n│   ├── docs\n│   │   ├── links.md\n│   │   └── loop.py\n│   ├── hello.go\n│   └── images\n│       ├── go-slices-usage-and-internals_slice-2.png\n│       ├── go.jpeg\n│       ├── rishikesh.jpeg\n│       └── rishikesh.png\n├── js\n│   ├── hello.js\n│   └── try\n│       └── examples\n│           └── dict-example.py\n├── main.md\n└── python\n    ├── examples\n    │   └── go\n    │       └── slice.go\n    ├── hello.py\n    └── images\n        ├── python.jpeg\n        └── rishikesh.webp\n\n```\n\n## Getting started\n\nNow, let's move/navigate to **root** directory which is to be assumed as the working directory in this documentation.\n\n```bash\nRishikeshs-MacBook-Air:try-pathlib hygull$ cd root/\nRishikeshs-MacBook-Air:root hygull$ ls\nc\tcpp\tdoc.md\tgo\tjs\tmain.md\tpython\nRishikeshs-MacBook-Air:root hygull$\n\n```\n\n```bash \nRishikeshs-MacBook-Air:root hygull$ python3\nPython 3.7.2 (default, Jan 13 2019, 12:50:01) \n[Clang 10.0.0 (clang-1000.11.45.5)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\u003e\u003e\u003e \n\n```\n\nWe are done, let's start.\n\n![try-pathlib-mac](./images/try-pathlib-28-feb-2019-01-05am.png)\n\n#### \u0026raquo; Listing out directories and files of current directory separately\n\n```python \n\u003e\u003e\u003e from pathlib import Path\n\u003e\u003e\u003e \n\u003e\u003e\u003e root = Path(\".\")\n\u003e\u003e\u003e root\nPosixPath('.')\n\u003e\u003e\u003e \n```\n\n```python\n\u003e\u003e\u003e directories = [dir_content for dir_content in root.iterdir() if dir_content.is_dir()]\n\u003e\u003e\u003e directories\n[PosixPath('go'), PosixPath('python'), PosixPath('js'), PosixPath('cpp'), PosixPath('c')]\n\u003e\u003e\u003e\n```\n\n```python \n\u003e\u003e\u003e files = [dir_content for dir_content in root.iterdir() if dir_content.is_file()]\n\u003e\u003e\u003e files\n[PosixPath('doc.md'), PosixPath('main.md')]\n\u003e\u003e\u003e \n\n```\n\n#### \u0026raquo; Getting absoute path of `root` directory\n\n```python\n\u003e\u003e\u003e root.absolute()\nPosixPath('/Users/hygull/Projects/Python3/try-pathlib/root')\n\u003e\u003e\u003e \n\n```\n\n#### \u0026raquo; Getting `home` directory's absolute path\n\n```python\n\u003e\u003e\u003e root.home()\nPosixPath('/Users/hygull')\n\n```\n\n#### \u0026raquo; Listing out all python files present in any of the directories availble under current directory\n\n```python\n\u003e\u003e\u003e list(root.glob(\"**/*.py\"))\n[PosixPath('go/docs/loop.py'), PosixPath('python/hello.py'), PosixPath('js/try/examples/dict-example.py')]\n\u003e\u003e\u003e \n\n\n```\n\n\n#### \u0026raquo; Navigating to `root/python/examples/go` and lisiting out its content(s).\n\n+ Brief look using terminal.\n\n```bash\nRishikeshs-MacBook-Air:root hygull$ \nRishikeshs-MacBook-Air:root hygull$ ls python/examples/\ngo\nRishikeshs-MacBook-Air:root hygull$ ls python/examples/go/\nslice.go\nRishikeshs-MacBook-Air:root hygull$ cat python/examples/go/slice.go \npackage main \n\nimport \"fmt\"\n\nfunc main() {\n\ta := []int{12, 5, 6, 8}\n\tfmt.Print(a)\n}\n\n```\n\n+ Prgramatically navigating to `root/python/examples/go` by verifying the navigated location's existence.\n\n```python\n\u003e\u003e\u003e root\nPosixPath('.')\n\u003e\u003e\u003e \n\u003e\u003e\u003e python = root / \"python\"\n\u003e\u003e\u003e python\nPosixPath('python')\n\u003e\u003e\u003e \n\u003e\u003e\u003e python.exists()\nTrue\n\u003e\u003e\u003e \n\u003e\u003e\u003e examples = python / \"examples\"\n\u003e\u003e\u003e examples\nPosixPath('python/examples')\n\u003e\u003e\u003e \n\u003e\u003e\u003e examples.exists()\nTrue\n\u003e\u003e\u003e \n\u003e\u003e\u003e go = examples / \"go\"\n\u003e\u003e\u003e go\nPosixPath('python/examples/go')\n\u003e\u003e\u003e \n\u003e\u003e\u003e go.exists()\nTrue\n\u003e\u003e\u003e \n\n```\n\n+ Lisiting out content(s) of **go** directory.\n\n```python\n\u003e\u003e\u003e list(go.iterdir())\n[PosixPath('python/examples/go/slice.go')]\n\u003e\u003e\u003e \n```\n\n+ Single line to navigate to `go` directory - `go = root / \"python\" / \"examples\" / \"go\"`\n\n```python\n\u003e\u003e\u003e examples = root / \"examples\"\n\u003e\u003e\u003e examples.exists()\nFalse\n\u003e\u003e\u003e \n\u003e\u003e\u003e examples = root / \"python\" / \"examples\"\n\u003e\u003e\u003e examples.exists()\nTrue\n\u003e\u003e\u003e \n```\n\n```python\n\u003e\u003e\u003e go = root / \"python\" / \"examples\" / \"go\"\n\u003e\u003e\u003e go.exists()\nTrue\n\u003e\u003e\u003e \n\n```\n\n#### \u0026raquo; Getting URI\n\n```python\n\u003e\u003e\u003e python\nPosixPath('python')\n\u003e\u003e\u003e \n```\n\n```python\n\u003e\u003e\u003e python.as_uri()\nTraceback (most recent call last):\n  File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\n  File \"/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py\", line 714, in as_uri\n    raise ValueError(\"relative path can't be expressed as a file URI\")\nValueError: relative path can't be expressed as a file URI\n\u003e\u003e\u003e \n```\n\n```python\n\u003e\u003e\u003e python = python.resolve()\n\u003e\u003e\u003e python\nPosixPath('/Users/hygull/Projects/Python3/try-pathlib/root/python')\n\u003e\u003e\u003e \n```\n\n```python\n\u003e\u003e\u003e python.as_uri()\n'file:///Users/hygull/Projects/Python3/try-pathlib/root/python'\n\u003e\u003e\u003e \n\n```\n\n\n#### \u0026raquo; Printing parent directories and checking their existence\n\n```python\n\u003e\u003e\u003e go = go.resolve()\n\u003e\u003e\u003e go.as_uri()\n'file:///Users/hygull/Projects/Python3/try-pathlib/root/python/examples/go'\n\u003e\u003e\u003e\n\n```\n\n```python\n\u003e\u003e\u003e examples = go.parent\n\u003e\u003e\u003e examples\nPosixPath('/Users/hygull/Projects/Python3/try-pathlib/root/python/examples')\n\u003e\u003e\u003e \n\u003e\u003e\u003e examples.exists()\nTrue\n\u003e\u003e\u003e \n\n```\n\n```python\n\u003e\u003e\u003e python = examples.parent\n\u003e\u003e\u003e python\nPosixPath('/Users/hygull/Projects/Python3/try-pathlib/root/python')\n\u003e\u003e\u003e \n\u003e\u003e\u003e python.exists()\nTrue\n\u003e\u003e\u003e \n```\n\n\n### \u0026raquo; Creating a directory with a file inside it with few lines\n\n\u003e The output of the below code is [created_files](./src/created_files) directory with [message.txt](./src/created_files/message.txt) file inside it.\n\n```python\n\"\"\"\n    {\n        \"date_created\": \"2 march 2019, Sat\",\n        \"aim\": \"Creating files with contents (few lines)\",\n        \"created_by\": \"Rishikesh Agrawani\",\n        \"description\": \"First the code will check if there is a directory \n                        named `created_files` in the current working directory\n                        if it exists, it will create files inside that\n                        it it doesn't exist, create the folder first and then create file\n                        named `message.txt` inside that\"\n\n    }\n\"\"\"\n\nfrom pathlib import Path \n\n\ncwd = Path(\".\")\ncreated_files_dir = cwd / \"created_files\"\n\nif not created_files_dir.exists():\n    created_files_dir.mkdir()\n\nfile = created_files_dir / \"message.txt\"\n\nlines = [\n    \"It is better to learn programming for solving complex problems.\",\n    \"Python, Java, Go, C, JavaScript, Ruby, PHP are popular.\",\n    \"So finally, we all are in a right place\"\n]\n\nfile.write_text('\\n'.join(lines))\n```\n\n# \u0026raquo; Creating directories in the current working directory\n\n+ Name of the directories are specified in a text file named [directory_names.txt](../docs/texts/directory_names.txt)\n\n+ Creates the directory names mentioned in the text file\n\n```python\n\"\"\"\n    {\n        \"date_created\": \"4 march 2019, Mon\",\n        \"aim\": \"Creating directories whose names are mentioned in a text file\",\n        \"created_by\": \"Rishikesh Agrawani\",\n        \"description\": \"First program will check if directory named `created_directories` exists or not\n                       If it does exist it creates that and after that it reads a text file \n                       `../docs/texts/directory_names.txt` to read list of directory names and create \n                       those directories inside `created_directories` directory.\n                       \n                       Here I have not coded for validations etc. so assume that I have valid names in \n                       the text file (check it)\"\n    }\n\"\"\"\n\nfrom pathlib import Path \n\n\ncwd = Path(\".\").resolve()\ncreated_directories_dir_path = cwd / \"created_directories\"\n\nif not created_directories_dir_path.exists():\n    created_directories_dir_path.mkdir()\n    print(\"Directory successfully created\")\n\n# Getting path of the file to be read\ndirectory_names_file_path = cwd.parent / \"docs\" / \"texts\" / \"directory_names.txt\"\n\nprint(directory_names_file_path) \nprint(directory_names_file_path.exists())\nprint(directory_names_file_path.is_file())\n\ndirectory_names = directory_names_file_path.read_text().split('\\n')\n\n# ['Gayle', 'Sachin', 'Sehwag', 'Garry', 'Dhoni', 'Ricky', 'Adam', 'Ken', 'Dennis', 'Wes']\nprint(directory_names) \n\nfor directory_name in directory_names:\n    directory_path = created_directories_dir_path / directory_name.strip()\n    directory_path.mkdir()\n    print(\"Created\", directory_path)\n\n# Storing absolute path of all the newly created directories\nnew_dir_paths = [str(new_dir_path) for new_dir_path in created_directories_dir_path.iterdir() if new_dir_path.is_dir()]\nprint(new_dir_paths)\n# ['/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sehwag', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dennis', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dhoni', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ricky', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Garry', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Gayle', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Wes', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sachin', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ken', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Adam']\n\n```\n\n\u003e Ouput\n\n```bash\nRishikeshs-MacBook-Air:src hygull$ python3 create_directories.py \nDirectory successfully created\n/Users/hygull/Projects/Python3/try-pathlib/docs/texts/directory_names.txt\nTrue\nTrue\n['Gayle', 'Sachin', 'Sehwag', 'Garry', 'Dhoni', 'Ricky', 'Adam', 'Ken', 'Dennis', 'Wes']\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Gayle\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sachin\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sehwag\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Garry\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dhoni\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ricky\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Adam\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ken\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dennis\nCreated /Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Wes\n['/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sehwag', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dennis', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Dhoni', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ricky', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Garry', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Gayle', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Wes', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Sachin', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Ken', '/Users/hygull/Projects/Python3/try-pathlib/src/created_directories/Adam']\n```\n\n\n## Help\n\n```python\n\u003e\u003e\u003e from pathlib import Path\n\u003e\u003e\u003e \n\u003e\u003e\u003e root = Path(\".\")\n\u003e\u003e\u003e \n\u003e\u003e\u003e dir(root)\n['__bytes__', '__class__', '__delattr__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__fspath__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rtruediv__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__truediv__', '_accessor', '_cached_cparts', '_closed', '_cparts', '_drv', '_flavour', '_format_parsed_parts', '_from_parsed_parts', '_from_parts', '_hash', '_init', '_make_child', '_make_child_relpath', '_opener', '_parse_args', '_parts', '_pparts', '_raise_closed', '_raw_open', '_root', '_str', 'absolute', 'anchor', 'as_posix', 'as_uri', 'chmod', 'cwd', 'drive', 'exists', 'expanduser', 'glob', 'group', 'home', 'is_absolute', 'is_block_device', 'is_char_device', 'is_dir', 'is_fifo', 'is_file', 'is_mount', 'is_reserved', 'is_socket', 'is_symlink', 'iterdir', 'joinpath', 'lchmod', 'lstat', 'match', 'mkdir', 'name', 'open', 'owner', 'parent', 'parents', 'parts', 'read_bytes', 'read_text', 'relative_to', 'rename', 'replace', 'resolve', 'rglob', 'rmdir', 'root', 'samefile', 'stat', 'stem', 'suffix', 'suffixes', 'symlink_to', 'touch', 'unlink', 'with_name', 'with_suffix', 'write_bytes', 'write_text']\n\u003e\u003e\u003e \n\u003e\u003e\u003e help(root)\n\n\u003e\u003e\u003e help(root.exists())\n\u003e\u003e\u003e \n\u003e\u003e\u003e help(root.as_uri)\n\n\u003e\u003e\u003e \n\n```\n\n## Screenshots\n\n![ScreenShot2019-03-02at8.26.27AM.png](./images/linkedin-article/ScreenShot2019-03-02at8.26.27AM.png)\n\n![ScreenShot2019-03-02at9.31.17AM.png](./images/linkedin-article/ScreenShot2019-03-02at9.31.17AM.png)\n\n![ScreenShot2019-03-02at12.31.04PM.png](./images/linkedin-article/ScreenShot2019-03-02at12.31.04PM.png)\n\n![ScreenShot2019-03-02at2.25.17PM.png](./images/linkedin-article/ScreenShot2019-03-02at2.25.17PM.png)\n\n![ScreenShot2019-03-02at2.40.59PM.png](./images/linkedin-article/ScreenShot2019-03-02at2.40.59PM.png)\n\n![ScreenShot2019-03-02at3.20.25PM.png](./images/linkedin-article/ScreenShot2019-03-02at3.20.25PM.png)\n\n![ScreenShot2019-03-02at3.33.55PM.png](./images/linkedin-article/ScreenShot2019-03-02at3.33.55PM.png)\n\n![ScreenShot2019-03-02at3.47.52PM.png](./images/linkedin-article/ScreenShot2019-03-02at3.47.52PM.png)\n\n\n## References\n\n+ [https://python.readthedocs.io/en/stable/library/pathlib.html](https://python.readthedocs.io/en/stable/library/pathlib.html)\n\n+ [https://pypi.org/project/pathlib/?fbclid=IwAR0-Jk14-IkTLCNldiHXvv5HAzhE_C71YDMdv9vmfT0QtlILYZku_7gLKSM](https://pypi.org/project/pathlib/?fbclid=IwAR0-Jk14-IkTLCNldiHXvv5HAzhE_C71YDMdv9vmfT0QtlILYZku_7gLKSM)\n\n+ [https://realpython.com/python-pathlib/](https://realpython.com/python-pathlib/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhygull%2Ftry-pathlib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhygull%2Ftry-pathlib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhygull%2Ftry-pathlib/lists"}