Files
sspai-100-hours-series-python/code/newsletter/N3/pathlib.ipynb

170 lines
3.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pathlib\n",
"path = pathlib.Path(\"~/Desktop/faker.py\").expanduser()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"PosixPath('/Users/Bobot/Desktop')"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path.parent"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'.py'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path.suffix"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'faker.py'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path.name"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# os version\n",
"\n",
"# import os\n",
"\n",
"# ROOT = os.path.expanduser(\"~/Desktop/test\")\n",
"# file = os.path.join(str(ROOT), \"prime.txt\")\n",
"\n",
"# if not os.path.exists(file):\n",
"# os.mkdir(ROOT)\n",
"# with open(file, mode=\"w+\", encoding=\"utf-8\") as f:\n",
"# f.write(\"Hello, World!\")\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import pathlib\n",
"\n",
"file = pathlib.Path(\"~/Desktop/test\").expanduser().joinpath(\"prime.txt\")\n",
"if not file.exists():\n",
" file.parent.mkdir(parents=True, exist_ok=True)\n",
" file.write_text(\"Hello, World!\", encoding=\"utf-8\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"PosixPath('/Users/Bobot/Desktop/test/echo.md')"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"file = (\n",
" pathlib.Path(\"~/Desktop/test\")\n",
" .expanduser()\n",
" .joinpath(\"prime.txt\")\n",
" .with_stem(\"echo\")\n",
" .with_suffix(\".md\")\n",
")\n",
"\n",
"file\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.0 ('pandas-startup')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "13977d4cc82dee5f9d9535ceb495bd0ab12a43c33c664e5f0d53c24cf634b67f"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}