Skip to content

Commit

Permalink
00 / 30 : add pathlib example
Browse files Browse the repository at this point in the history
Clean ipynb b487e2b
  • Loading branch information
beachdweller committed Nov 20, 2024
1 parent b9cc272 commit 55698d0
Showing 1 changed file with 74 additions and 1 deletion.
75 changes: 74 additions & 1 deletion 00_introduction/30_python_review_2.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,79 @@
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## File I/O\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `pathlib`\n",
"* `pathlib` : Object oriented file system paths in the python standard library<br>파이썬 표준 라이브러리 내 객체 지향 파일 경로\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pathlib\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# pathlib.Path to a possible new temporary folder\n",
"tmp_path = pathlib.Path('temporary_folder')\n",
"\n",
"# create the new temporary folder\n",
"# exist_ok: no \"folder already exists\" error even if the folder is already there\n",
"tmp_path.mkdir(exist_ok=True)\n",
"\n",
"# pathlib.Path to a possible new file\n",
"new_file = tmp_path / 'my_new_file.txt'\n",
"\n",
"bytes_written = 0\n",
"\n",
"# open the file in text write mode\n",
"with new_file.open('wt', encoding='utf-8') as tmp_file:\n",
" for i in range(10):\n",
" # write a text line to the temporary file\n",
" bytes_written += tmp_file.write(f'i = {i} i*i = {i*i}\\n')\n",
"# file closed\n",
"\n",
"print(f'bytes_written = {bytes_written}')\n",
"\n",
"bytes_read = 0\n",
"# open the temporary file in text read mode\n",
"with new_file.open('rt', encoding='utf-8') as read_file:\n",
" # iterating through a file will fetch one line at a time\n",
" for k, line in enumerate(read_file):\n",
" txt = f'line {k:2d} : {line}'\n",
" print(txt)\n",
" bytes_read += len(line)\n",
"# file closed\n",
"\n",
"print(f'bytes_read = {bytes_read}')\n",
"\n",
"# when the task is done, remove the file & folder\n",
"new_file.unlink()\n",
"# works only when the folder is empty\n",
"tmp_path.rmdir()\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -770,7 +843,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.0"
"version": "3.10.9"
}
},
"nbformat": 4,
Expand Down

0 comments on commit 55698d0

Please sign in to comment.