Skip to content

Instantly share code, notes, and snippets.

@yunwoong7
Last active June 8, 2023 11:13
Show Gist options
  • Save yunwoong7/b02fa46e7fef7c86d8461b9b5a70bfd2 to your computer and use it in GitHub Desktop.
Save yunwoong7/b02fa46e7fef7c86d8461b9b5a70bfd2 to your computer and use it in GitHub Desktop.
[ Python ] 파일명, 디렉토리 경로 추출
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "f51da98c-033d-44ae-a41d-d09982fe3807",
"metadata": {},
"source": [
"# 파일명, 디렉토리 경로 추출"
]
},
{
"cell_type": "markdown",
"id": "e3908d89-3209-45b0-83f5-a820b5d91e78",
"metadata": {},
"source": [
"## 1. 파일 목록 얻기"
]
},
{
"cell_type": "markdown",
"id": "ebd0b932-648e-4e79-849f-693c52124dec",
"metadata": {},
"source": [
"### 1) glob\n",
"glob 모듈의 glob 함수는 조건에 해당하는 파일명을 리스트 형식으로 Return"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "5824cbaf-a0e3-4883-9745-f37a91e8d529",
"metadata": {},
"outputs": [],
"source": [
"import glob"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b25e10cb-3459-4f2f-89f1-cfbbeb3103d3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['asset/images\\\\test_image.jpg', 'asset/images\\\\test_image2.jpg']\n"
]
}
],
"source": [
"path = 'asset/images/*'\n",
"output = glob.glob(path)\n",
"print(output)"
]
},
{
"cell_type": "markdown",
"id": "668f0ad7-a9a3-4ba5-b922-061ace828000",
"metadata": {},
"source": [
"그 밖의 사용방법\n",
" * '*'는 임의 길이의 모든 문자열을 의미 \n",
" * '?'는 한자리의 문자를 의미 \n",
" * recursive=True로 설정하고 '**'를 사용하면 모든 하위 디렉토리까지 탐색\n",
" \n",
"```python\n",
"glob.glob('./[0-9].*')\n",
">> ['./1.gif', './2.txt']\n",
"\n",
"glob.glob('*.gif')\n",
">> ['1.gif', 'test.gif']\n",
"\n",
"glob.glob('?.gif')\n",
">> ['1.gif']\n",
"\n",
"glob.glob('**/*.txt', recursive=True)\n",
">>['2.txt', 'sub/3.txt']\n",
"\n",
"glob.glob('./**/', recursive=True)\n",
">> ['./', './sub/']\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "d8ccecf6-6068-437d-ad56-9086946553a8",
"metadata": {},
"source": [
"### 2) os.listdir() Method\n",
"지정한 경로의 내의 모든 파일명과 디렉토리를 리스트 형식으로 Return"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "67cc3918-5cce-43ee-9299-20656aa314cd",
"metadata": {},
"outputs": [],
"source": [
"import os"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "45aa2177-4d13-41a5-9724-12bfd3af26d9",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['.ipynb_checkpoints', 'test_image.jpg', 'test_image2.jpg']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path = 'asset/images/'\n",
"os.listdir(path)"
]
},
{
"cell_type": "markdown",
"id": "ec9f64dd-6ed3-461b-98be-330a41754e2b",
"metadata": {},
"source": [
"원하는 파일 확장자만 추출하는 경우"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "9311b71d-fcd2-4228-a9ce-c901eb4df8ae",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['test_image.jpg', 'test_image2.jpg']"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"file_list = os.listdir(path)\n",
"jpg_file_list = [file for file in file_list if file.endswith(\".jpg\")]\n",
"jpg_file_list"
]
},
{
"cell_type": "markdown",
"id": "ac37204e-9b5b-4236-97ed-8a6e28ea6ab8",
"metadata": {},
"source": [
"**차이점은 glob으로 파일 리스트를 가져올 경우에는 검색시 사용했던 전체 경로 ```asset/images\\\\test_image.jpg'``` 를 os.listdir를 사용하면 파일명만 ```'test_image.jpg'``` 가져옴**"
]
},
{
"cell_type": "markdown",
"id": "974d5062-cd65-44e0-a067-d5cf9a8187d0",
"metadata": {},
"source": [
"### 3) dircache.listdir() Method\n",
"os.listdir(path)와 동일한 결과를 Return\n",
"path가 변경되지 않았을 때, dircache.listdir()은 다시 디렉토리 구조를 읽지 않고 이미 읽은 정보를 활용 \n",
"*python2까지만 지원되며 **python3에서는 지원되지 않습니다.***"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "1ceecef4-02c3-49b1-8646-f7429f81b75a",
"metadata": {},
"outputs": [],
"source": [
"import dircache"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "edf0119d-6870-48e1-a610-495b5cb1329a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['.ipynb_checkpoints', 'test_image.jpg', 'test_image2.jpg']"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path = 'asset/images/'\n",
"dircache.listdir(path)"
]
},
{
"cell_type": "markdown",
"id": "791c3eae-0751-40f9-814b-d1da481bd4c2",
"metadata": {},
"source": [
"일반 파일명과 디렉토리명을 구분해주는 함수"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "ea0d7faa-8ece-4e68-ab47-0f0d09b6609c",
"metadata": {},
"outputs": [],
"source": [
"dircache.annotate(head, list)"
]
},
{
"cell_type": "markdown",
"id": "cc3868ea-c377-4128-b355-551183a73e28",
"metadata": {},
"source": [
"---\n",
"## 2. 파일, 디렉토리"
]
},
{
"cell_type": "markdown",
"id": "d08912e2-d0ca-4c50-9083-19c03e84bcb3",
"metadata": {},
"source": [
"### 1) 현재 프로세스의 작업 디렉토리 얻기"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "ff9bc7c6-bd37-4997-a502-48a75916608a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'D:\\\\PycharmProjects\\\\Basic'"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.getcwd()"
]
},
{
"cell_type": "markdown",
"id": "940dae45-dc2f-4cf3-aab0-ebbc6d4419b5",
"metadata": {},
"source": [
"### 2) 작업하고 있는 디렉토리 변경"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "1be4384c-ad91-438a-ac69-6b051a61617b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"path = \"D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\"\n",
"os.chdir(path)\n",
"os.getcwd()"
]
},
{
"cell_type": "markdown",
"id": "013cff26-2278-4b28-b7dd-60d1cb11059b",
"metadata": {},
"source": [
"현재 경로 위치에서 부모 디렉토리로 이동하는 방법"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "6b61241b-7eca-4749-a040-8f7a77920450",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"현재 디렉토리 : D:\\PycharmProjects\\Basic\\asset\\images\n",
"변경후 디렉토리 : D:\\PycharmProjects\\Basic\\asset\n"
]
}
],
"source": [
"print(\"현재 디렉토리 : {}\".format(os.getcwd()))\n",
"os.chdir(\"../\")\n",
"print(\"변경후 디렉토리 : {}\".format(os.getcwd()))"
]
},
{
"cell_type": "markdown",
"id": "da8f7f0a-b78e-4efd-89ef-222bce1fd58a",
"metadata": {},
"source": [
"### 3) 디렉토리 생성\n",
"```os.mkdir```와 ```os.makedirs```의 차이점은 mkdir은 **한 폴더만 생성**이 가능합니다. ```'./new_folder'``` \n",
"makedirs는 ```'./new_folder1/new_folder2/new_folde3'``` 처럼 **한번에 원하는 만큼 디렉토리를 생성**할 수 있습니다. exist_ok라는 Argument는 True로 하면 해당 디렉토리가 기존에 존재하면 에러발생 없이 넘어가고, 없을 경우에만 생성합니다."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "4e94bbe8-0567-41d5-9cc0-57db40baa462",
"metadata": {},
"outputs": [],
"source": [
"os.mkdir(\"new_folder\")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "6c5027b3-2609-4bc9-bab2-438dd0affe30",
"metadata": {},
"outputs": [],
"source": [
"os.makedirs(\"new_folder\", exist_ok=True)"
]
},
{
"cell_type": "markdown",
"id": "8149bf14-b4ac-4b91-b77d-fef3ea71df85",
"metadata": {},
"source": [
"### 4) 파일이나 디렉토리 지우기\n",
"```os.remove( filename or path )```\n",
"os.remove Method를 이용하여 삭제 시 파일이 존재하거나 다른 액세스가 있는 경우 ```PermissionError: [WinError 5] 액세스가 거부되었습니다``` 에러가 발생합니다."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "18a0a53b-f735-47dc-88fc-36cd92e4ce91",
"metadata": {},
"outputs": [],
"source": [
"# os.remove(\"new_folder\")"
]
},
{
"cell_type": "markdown",
"id": "15570d34-1511-47e6-97f6-dc80de4f0d73",
"metadata": {},
"source": [
"```shutil.rmtree()```는 전체 디렉토리 트리, 즉 그 안에있는 모든 파일과 하위 디렉토리를 삭제합니다. 입력 인수가 디렉토리가 아니거나 존재하지 않거나 사용자에게 디렉토리를 삭제할 권한이없는 경우는 예외가 발생합니다."
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "58b6950e-c99f-40b7-bc0c-1f9daadb6377",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The directory is deleted successfully\n"
]
}
],
"source": [
"import shutil\n",
"\n",
"try:\n",
" shutil.rmtree(\"new_folder\")\n",
"except OSError as e:\n",
" print(e)\n",
"else:\n",
" print(\"The directory is deleted successfully\")"
]
},
{
"cell_type": "markdown",
"id": "4a75b3d6-641b-4f20-bff8-23ce83308dcd",
"metadata": {},
"source": [
"### 5) 파일의 상대 경로를 절대 경로로 바꾸는 함수"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "d3e8a1dc-cbda-4d07-a5b6-83ca95935d11",
"metadata": {},
"outputs": [],
"source": [
"filename = 'images\\\\test_image.jpg'"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "53d437ea-c099-4f5e-9319-68ee4c6cb73b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image.jpg'"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.abspath(filename)"
]
},
{
"cell_type": "markdown",
"id": "e9d95c3e-f33e-4b3f-935f-ee67a6465462",
"metadata": {},
"source": [
"### 6) 주어진 경로에 파일 혹은 디렉토리가 존재하는지 체크\n",
"#### 파일 혹은 디렉토리 체크"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "e15f68ea-7473-422c-9e25-d4cb33d085a3",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.exists(filename)"
]
},
{
"cell_type": "markdown",
"id": "fa1207b4-3738-46af-bd4e-184ed6f9d933",
"metadata": {},
"source": [
"#### 디렉토리 경로가 존재하는지 체크"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "aeff999d-7bf3-4c9f-9095-c82d688f8782",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.isdir(\"D:\\\\PycharmProjects\")"
]
},
{
"cell_type": "markdown",
"id": "045b7892-7b82-4281-9589-63d484de83c0",
"metadata": {},
"source": [
"#### 파일이 경로가 존재하는지 체크"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "37945a7b-cb30-4abc-827d-cd24b73451e6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.isfile(filename)"
]
},
{
"cell_type": "markdown",
"id": "bd24c5f2-9b64-44b1-b897-08b9bd47f31f",
"metadata": {},
"source": [
"### 7) 디렉토리 지정 텍스트\n",
"#### 현재 디렉토리"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "a7d686f2-eea2-4d0c-b321-7392a79696e8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'.'"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.curdir"
]
},
{
"cell_type": "markdown",
"id": "18476f8d-e3ec-4c7c-8533-b96c7c22b53d",
"metadata": {},
"source": [
"#### 부모 디렉토리를 지정 텍스트"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "eb31260b-c74c-422b-a5ac-f9901870690c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'..'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.pardir"
]
},
{
"cell_type": "markdown",
"id": "a6f9bba4-49a3-4e6a-adff-dd5a98200313",
"metadata": {},
"source": [
"#### 디렉토리 분리 텍스트\n",
"windows는 \\ linux는 / 를 반환한다."
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "2fec4e3e-fbd3-462f-bb46-8defff38546a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'\\\\'"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.sep"
]
},
{
"cell_type": "markdown",
"id": "5abf13b2-26c9-4f4e-be77-1021c28682ea",
"metadata": {},
"source": [
"### 8) 부모 디렉토리 얻기"
]
},
{
"cell_type": "markdown",
"id": "d2e2f31a-cc96-47ee-a990-cc73107c7443",
"metadata": {},
"source": [
"#### os.pardir() Method"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "f94d0d85-24d5-4220-8cde-c80969b4d6c8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"D:\\PycharmProjects\\Basic\\asset\\images\n"
]
}
],
"source": [
"filename = 'D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image.jpg'\n",
"print(os.path.abspath(os.path.join(filename, os.pardir)))"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "5626ab9e-3233-496b-af92-7908c7c2185f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"D:\\PycharmProjects\\Basic\\asset\\images\n"
]
}
],
"source": [
"print(os.path.abspath(os.path.join(filename, '..')))"
]
},
{
"cell_type": "markdown",
"id": "4d30d52b-d7f7-42ce-95f6-86c1ec31c1d9",
"metadata": {},
"source": [
"#### os.dirname() Method"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "b4bb8e0e-d0fb-446e-a208-d01569797ece",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"D:\\PycharmProjects\\Basic\\asset\\images\n"
]
}
],
"source": [
"print(os.path.dirname(filename))"
]
},
{
"cell_type": "markdown",
"id": "e57db96b-40a8-4a0a-833e-ec0c3f6dccd1",
"metadata": {},
"source": [
"#### pathlib모듈의path.parent() Method"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "d86da08c-33a1-4e01-9b0d-f85c5672c796",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"WindowsPath('D:/PycharmProjects/Basic/asset/images')"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"\n",
"filename = Path('D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image.jpg')\n",
"filename.parent"
]
},
{
"cell_type": "markdown",
"id": "9aaa7feb-b865-4b22-929f-2dabfa9bf4b3",
"metadata": {},
"source": [
"## 3. 경로분리"
]
},
{
"cell_type": "markdown",
"id": "fc0f5398-bbc9-499f-955d-f61f7668e023",
"metadata": {},
"source": [
"### 1) 파일명만 추출"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "cd455036-d099-45eb-b218-8cf660727778",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'test_image.jpg'"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"filename = 'D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image.jpg'\n",
"os.path.basename(filename)"
]
},
{
"cell_type": "markdown",
"id": "ee1a6985-2efb-44b2-91d5-8c89ebfc5cf0",
"metadata": {},
"source": [
"### 2) 디렉토리 경로 추출"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "caf561d4-ddff-4ff5-8f13-c84b7faeb298",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images'"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.dirname(filename)"
]
},
{
"cell_type": "markdown",
"id": "279dfa1a-86cf-4c5e-8f22-d642c9c1943a",
"metadata": {},
"source": [
"### 3) 경로와 파일명을 분리"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "195706ba-2028-4b0b-922b-e7436e61c024",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images', 'test_image.jpg')"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.split(filename)"
]
},
{
"cell_type": "markdown",
"id": "1d98da72-6a86-48cb-a0bb-5bbeb7117646",
"metadata": {},
"source": [
"경로에 포함된 각 폴더의 이름 및 파일의 이름을 리스트로 Return"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "f883c797-11e2-4b79-8bc5-2b514d0050ff",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['D:', 'PycharmProjects', 'Basic', 'asset', 'images', 'test_image.jpg']"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"filename.split('\\\\')"
]
},
{
"cell_type": "markdown",
"id": "654e9dda-e6ab-49ca-a1ac-4c4744d37a98",
"metadata": {},
"source": [
"### 4) 드라이브명과 나머지 분리 (MS Windows의 경우)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "1c42fe71-04e4-4b2e-9b70-15eaeb5b168c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('D:', '\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image.jpg')"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.splitdrive(filename) "
]
},
{
"cell_type": "markdown",
"id": "6b7cf492-105e-43a5-ad99-73fe9ad49ce5",
"metadata": {},
"source": [
"### 5) 확장자와 나머지 분리"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "83f49c87-1a13-4d4d-bc99-c5b604a4370b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('D:\\\\PycharmProjects\\\\Basic\\\\asset\\\\images\\\\test_image', '.jpg')"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.splitext(filename)"
]
},
{
"cell_type": "markdown",
"id": "5b3a3e13-9bd3-4189-a7f5-515d9b70e72f",
"metadata": {},
"source": [
"### 6) 경로를 병합하여 새로운 경로 생성"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "4796befd-b540-4617-9c01-f9c29cbe2863",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'D:\\\\PycharmProjects\\\\New_folder\\\\A'"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"os.path.join('D:\\PycharmProjects', 'New_folder', 'A')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "skt_sol_32_env",
"language": "python",
"name": "skt_sol_32_env"
},
"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.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment